【问题标题】:Concatenate a list of pandas dataframes together将熊猫数据框列表连接在一起
【发布时间】:2015-12-03 07:58:32
【问题描述】:

我有一个 Pandas 数据框列表,我想将它们组合成一个 Pandas 数据框。我正在使用 Python 2.7.10 和 Pandas 0.16.2

我从以下位置创建了数据框列表:

import pandas as pd
dfs = []
sqlall = "select * from mytable"

for chunk in pd.read_sql_query(sqlall , cnxn, chunksize=10000):
    dfs.append(chunk)

这会返回一个数据框列表

type(dfs[0])
Out[6]: pandas.core.frame.DataFrame

type(dfs)
Out[7]: list

len(dfs)
Out[8]: 408

这是一些示例数据

# sample dataframes
d1 = pd.DataFrame({'one' : [1., 2., 3., 4.], 'two' : [4., 3., 2., 1.]})
d2 = pd.DataFrame({'one' : [5., 6., 7., 8.], 'two' : [9., 10., 11., 12.]})
d3 = pd.DataFrame({'one' : [15., 16., 17., 18.], 'two' : [19., 10., 11., 12.]})

# list of dataframes
mydfs = [d1, d2, d3]

我想将d1d2d3 组合成一个熊猫数据框。或者,在使用 chunksize 选项时将大型表直接读取到数据框中的方法将非常有帮助。

【问题讨论】:

    标签: python pandas dataframe concat


    【解决方案1】:

    鉴于所有数据框都有相同的列,您可以简单地 concat 它们:

    import pandas as pd
    df = pd.concat(list_of_dataframes)
    

    【讨论】:

      【解决方案2】:

      如果数据框并非都具有相同的列,请尝试以下操作:

      df = pd.DataFrame.from_dict(map(dict,df_list))
      

      【讨论】:

      • 此解决方案不适用于我在 Python 3.6.5 / Pandas v0.23.0 上。它与TypeError: data argument can't be an iterator 出错。首先转换为list(模仿Python 2.7)也会产生意想不到的结果。
      • 如果所有数据框都有相同的列,我们应该怎么做?
      【解决方案3】:

      你也可以用函数式编程来做到这一点:

      from functools import reduce
      reduce(lambda df1, df2: df1.merge(df2, "outer"), mydfs)
      

      【讨论】:

      • from functools import reduce 使用reduce
      • 不建议对多个 DataFrame 进行成对合并,这根本没有效率。请参阅pd.concatjoin,默认情况下都接受帧列表并加入索引。
      【解决方案4】:

      只是添加更多细节:

      例子:

      list1 = [df1, df2, df3]
      
      import pandas as pd
      
      • 逐行连接和忽略索引

        pd.concat(list1, axis=0, ignore_index=True)
        

        注意:如果列名不同,则 NaN 将插入不同的列值

      • 按列连接并希望保留列名

        pd.concat(list1, axis=1, ignore_index=False)
        

        如果ignore_index=True,列名将填充从0到(n-1)的数字,其中n是唯一列名的计数

      【讨论】:

        【解决方案5】:

        concat 还可以很好地与使用“loc”命令针对现有数据帧提取的列表理解配合使用

        df = pd.read_csv('./data.csv') # ie; Dataframe pulled from csv file with a "userID" column
        
        review_ids = ['1','2','3'] # ie; ID values to grab from DataFrame
        
        # Gets rows in df where IDs match in the userID column and combines them 
        
        dfa = pd.concat([df.loc[df['userID'] == x] for x in review_ids])
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-10-09
          • 2019-07-23
          • 2021-07-12
          • 2020-10-13
          • 2019-02-15
          相关资源
          最近更新 更多