如何有效地连接由 for 循环生成的数千个 pandas 数据帧?

How to concat thousands of pandas dataframes generated by a for loop efficiently?

在读取不同文件的 for 循环中生成了数以千计的一致列的 df,我正在尝试将它们合并/连接/附加到单个 df,combined:

combined = pd.DataFrame()

for i in range(1,1000): # demo only
    global combined
    generate_df() # df is created here
    combined = pd.concat([combined, df])

这最初很快,但随着 combined 的增长而变慢,最终变得慢得无法使用。 解释了如何将行添加到 dict 然后创建 df 是最有效的,但我无法弄清楚如何使用 to_dict.

有什么好的方法吗?我是不是用错了方法?

您可以创建 DataFrame 列表,然后只使用 concat 一次:

dfs = []

for i in range(1,1000): # demo only
    global combined
    generate_df() # df is created here
    dfs.append(df)

combined = pd.concat(dfs)

最快的方法是构建一个字典列表,最后只构建一次数据框:

rows = []

for i in range(1, 1000):
    # Instead of generating a dataframe, generate a dictionary
    dictionary = generate_dictionary()
    rows.append(dictionary)

combined = pd.DataFrame(rows)

这比连接数据帧快大约 100 倍,benchmark here.

证明了这一点
  • 最后只使用一次concat
  • 对每个DataFrame的索引进行排序。在我的生产代码中,这种排序并没有花费很长时间,但将 concat 的处理时间从 10 多秒减少到不到一秒!

dfs = []

for i in range(1,1000): # demo only
    global combined
    df = generate_df() # df is created here
    df.sort_index(inplace=True)    
    dfs.append(df)

combined = pd.concat(dfs)