【问题标题】:How to concat thousands of pandas dataframes generated by a for loop efficiently?如何有效地连接由 for 循环生成的数千个 pandas 数据帧?
【发布时间】:2021-04-22 16:35:14
【问题描述】:

在读取不同文件的 for 循环中生成了数千个一致列的 dfs,我正在尝试将它们合并/连接/附加到单个 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 的增长而变慢,最终变得无法使用。 This answer on how to append rows 解释了如何将行添加到 dict 然后创建 df 是最有效的,但我不知道如何使用 to_dict 做到这一点。

有什么好的方法来解决这个问题?我是不是走错了路?

【问题讨论】:

    标签: python pandas dataframe append


    【解决方案1】:
    • 最后只使用一次concat
    • 对每个DataFrame的索引进行排序。在我的生产代码中,这种排序并没有花费很长时间,但将 concat 的处理时间从 10 + 秒减少到不到 1 秒!

    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)
    

    【讨论】:

      【解决方案2】:

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

      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)
      

      正如benchmark here 所证明的那样,这比连接数据帧快大约 100 倍。

      【讨论】:

        【解决方案3】:

        您可以创建 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)
        

        【讨论】:

        • 啊,太棒了。我错误地认为将同名的 dfs 附加到列表中是行不通的,但这是完美的。谢谢!
        猜你喜欢
        • 2022-01-04
        • 2020-08-14
        • 2019-06-21
        • 2022-01-04
        • 2022-01-23
        相关资源
        最近更新 更多