gpt4 book ai didi

python - 为什么以及何时在 Pandas 中使用 append() 而不是 concat()?

转载 作者:行者123 更新时间:2023-12-05 03:46:33 28 4
gpt4 key购买 nike

我已经阅读了所有关于 appendconcat 的主题,但仍然:如果 concat 具有相同的选项和功能,我为什么要使用 append

如有错误请指正

  • append() :可以同时追加两个数据帧;它与 axis=0
  • 中的 concat 相同
  • concat() : 可以连接多个 DF

要连接多个 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 的便捷方法。如果您查看 implementationappend 方法中,您会看到这一点。

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,
)

至于性能。在循环中一遍又一遍地调用这两个方法的计算量可能很大。您应该只创建一个列表并在完成循环后进行一次连接。

来自 docs :

iteratively appending rows to a DataFrame can be more computationallyintensive than a single concatenate. A better solution is to appendthose rows to a list and then concatenate the list with the originalDataFrame all at once.

关于python - 为什么以及何时在 Pandas 中使用 append() 而不是 concat()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65250202/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com