首页 > 解决方案 > 为什么以及何时在 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)`

正确的?

标签: pythonpandas

解决方案


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 一次性连接起来。


推荐阅读