首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >修复与熊猫附加函数相关的FutureWarning

修复与熊猫附加函数相关的FutureWarning
EN

Stack Overflow用户
提问于 2022-06-17 09:43:58
回答 1查看 5.7K关注 0票数 2

我在我的Python代码中获得了以下FutureWarning:

FutureWarning: frame.append方法已被废弃,并将在未来的版本中从熊猫中删除。使用pandas.concat代替。

现在,我在代码的各个部分中使用附加函数向现有的DataFrame添加行。

示例1:

代码语言:javascript
运行
复制
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:

代码语言:javascript
运行
复制
row2 = {'date': tmp_date, 'false_negatives': fn, 'total': total}
df2 = df2.append(row2, ignore_index = True)

如何在不修改前面章节之前的大部分代码的情况下,以简单的方式解决这个问题?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-06-17 09:52:45

使用pd.concat而不是追加。最好是同时出现在一堆行上。此外,尽可能使用date_range和timedelta_range。

示例1:

代码语言:javascript
运行
复制
# 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)
代码语言:javascript
运行
复制
# 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

不要看到上下文,所以很难知道什么是合适的。这两种中的一种

代码语言:javascript
运行
复制
# 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中,并将更大的数据文件连接在一起是可行的方法。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72657415

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档