我在我的Python代码中获得了以下FutureWarning:
FutureWarning: frame.append方法已被废弃,并将在未来的版本中从熊猫中删除。使用pandas.concat代替。
现在,我在代码的各个部分中使用附加函数向现有的DataFrame添加行。
示例1:
init_hour = pd.to_datetime('00:00:00')
orig_hour = init_hour+timedelta(days=1)
while init_hour < orig_hour:
row = {'Hours': init_hour.time()}
df = df.append(row, ignore_index = True)
init_hour = init_hour + timedelta(minutes=60)
示例2:
row2 = {'date': tmp_date, 'false_negatives': fn, 'total': total}
df2 = df2.append(row2, ignore_index = True)
如何在不修改前面章节之前的大部分代码的情况下,以简单的方式解决这个问题?
发布于 2022-06-17 09:52:45
使用pd.concat
而不是追加。最好是同时出现在一堆行上。此外,尽可能使用date_range和timedelta_range。
示例1:
# First transformation
init_hour = pd.to_datetime('00:00:00')
orig_hour = init_hour+timedelta(days=1)
rows = []
while init_hour < orig_hour:
rows.append({'Hours': init_hour.time()})
init_hour = init_hour + timedelta(minutes=60)
df = pd.concat([df, pd.DataFrame(rows)], axis=0, ignore_index=True)
# Second transformation - just construct it without loop
hours = pd.Series(pd.date_range("00:00:00", periods=24, freq="H").time, name="Hours")
# Then insert/concat hours into your dataframe.
示例2
不要看到上下文,所以很难知道什么是合适的。这两种中的一种
# Alternative 1
row2 = {'date': tmp_date, 'false_negatives': fn, 'total': total}
row2df = pd.DataFrame.from_records([row2])
df2 = pd.concat([df2, row2df], ignore_index=True, axis=0) # how to handle index depends on context
# Alternative 2
# assuming integer monotonic index - assign a new row with loc
new_index = len(df2.index)
df2.loc[new_index] = row2
注意:有理由不推荐附加内容。逐行使用它会导致非常慢的代码。因此,重要的是,我们要做的不仅仅是代码的本地转换,在分析运行时不要浪费计算机时间。
熊猫的作者们正试图让我们理解和欣赏用更有效的方法,即不逐行连接或建立数据框架。将多个行合并到一个DataFrame中,并将更大的数据文件连接在一起是可行的方法。
https://stackoverflow.com/questions/72657415
复制相似问题