python - 为什么以及何时在 Pandas 中使用 append() 而不是 concat()?
问题描述
我已经阅读了关于 append vs concat here的所有主题,但仍然......如果 concat 具有相同的选项和功能,为什么我应该使用 append ?
如果我错了,请纠正我。
append()
- 可以一次附加两个数据帧 - 与 concat in 相同axis=0
concat()
- 可以集中多个DF
为什么我应该在 for 循环中使用 append ?它更快吗?
让我们假设我正在从不同的文件打开 DF,例如:
df = pd.DataFrame()
for file in file_folder:
df = df.append(pd.read_csv(file))
OR
df = pd.DataFrame()
for file in file_folder:
df = pd.concat([df, pd.read_csv(file)])
输出是一样的。所以为什么?
编辑:为了加快速度,我应该这样做:
df_list = []
for file in file_folder:
df_list.append(pd.read_csv(file))
#and then use concat
df_all = pd.concat(df_list)`
正确的?
解决方案
append
是一种在后台调用的便捷方法concat
。如果您查看该方法的实现append
,您将看到这一点。
def append(...
...
if isinstance(other, (list, tuple)):
to_concat = [self, *other]
else:
to_concat = [self, other]
return concat(
to_concat,
ignore_index=ignore_index,
verify_integrity=verify_integrity,
sort=sort,
)
至于表现。在循环中一遍又一遍地调用这两种方法可能在计算上很昂贵。您应该在完成循环后创建一个列表并进行一次连接。
来自文档:
迭代地将行附加到 DataFrame 可能比单个连接的计算量更大。更好的解决方案是将这些行附加到列表中,然后将列表与原始 DataFrame 一次性连接起来。
推荐阅读
- javascript - Javascript:限制索引周围的数组
- firebase - firebase 可以处理多少用户?
- java - redis模板有查询语言吗?
- node.js - NodeJS 以 JSON 格式获取 LDAP 用户
- python - 有没有办法在使用熊猫按第三列中的值分组时将两列中的值相乘?
- flutter - 在颤振中使用 photo_manager 包的自定义媒体(图片和视频)不起作用
- amazon-web-services - Fargate - 如何在同一任务定义中对另一个容器进行 API 调用
- c - 如何在 C 中接受文件参数?
- kotlin - 如何在 Kotlin 中合并嵌套地图
- javascript - JavaScript Array of Objects to Array of Arrays Grouped by Object Prop Value