我有一个熊猫数据框架的列表,我想合并成一个熊猫数据框架。我使用的是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]

我想把d1, d2和d3合并到一个熊猫数据框架中。或者,当使用chunksize选项时,将一个较大的表直接读入数据帧的方法将非常有用。


当前回答

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

其他回答

假设所有的数据框架都有相同的列,你可以简单地连接它们:

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

Panders concat作品也以及与functools

from functors import reduce as reduce
import pandas as pd;
deaf = pd.read_csv("http://www.aol.com/users/data.csv")
for q in range(0, Len(deaf)):
  new = map(lambda x: reduce(pd.concat(x))

如果数据帧不都有相同的列,请尝试以下方法:

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

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

你也可以用函数式编程来实现:

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