从DataFrames字典创建DataFrame(Create a DataFrame from a dictionary of DataFrames)

我有一个DataFrames字典,其中键被认为是有意义的:

In [32]: x = pd.DataFrame(dict(foo=[1,2,3], bar=[4,5,6])).set_index('foo') In [33]: y = pd.DataFrame(dict(foo=[7,8,9], bar=[10,11,12])).set_index('foo') In [34]: z = dict(x=x, y=y)

看起来像:

In [43]: x Out[43]: bar foo 1 4 2 5 3 6 In [44]: y Out[44]: bar foo 7 10 8 11 9 12

有一个很好的方法来获取以下DataFrame:

foo bar x 1 4 2 5 3 6 y 7 10 8 11 9 12

I have a dictionary of DataFrames, where the keys are assumed to be meaningful:

In [32]: x = pd.DataFrame(dict(foo=[1,2,3], bar=[4,5,6])).set_index('foo') In [33]: y = pd.DataFrame(dict(foo=[7,8,9], bar=[10,11,12])).set_index('foo') In [34]: z = dict(x=x, y=y)

Which looks like:

In [43]: x Out[43]: bar foo 1 4 2 5 3 6 In [44]: y Out[44]: bar foo 7 10 8 11 9 12

Is there a nice way to get the following DataFrame:

foo bar x 1 4 2 5 3 6 y 7 10 8 11 9 12

最满意答案

您可以使用concat ,字典的键将自动用于新的索引级别:

In [6]: z = dict(x=x, y=y) In [7]: pd.concat(z) Out[7]: bar foo x 1 4 2 5 3 6 y 7 10 8 11 9 12

您还可以使用concat的names参数为此新索引级别指定名称(例如names=['key'] )。

You can use concat for this, and the keys of the dictionary will automatically be used for a new index level:

In [6]: z = dict(x=x, y=y) In [7]: pd.concat(z) Out[7]: bar foo x 1 4 2 5 3 6 y 7 10 8 11 9 12

You can also give this new index level a name using the names argument of concat (eg names=['key']).

从DataFrames字典创建DataFrame(Create a DataFrame from a dictionary of DataFrames)

我有一个DataFrames字典,其中键被认为是有意义的:

In [32]: x = pd.DataFrame(dict(foo=[1,2,3], bar=[4,5,6])).set_index('foo') In [33]: y = pd.DataFrame(dict(foo=[7,8,9], bar=[10,11,12])).set_index('foo') In [34]: z = dict(x=x, y=y)

看起来像:

In [43]: x Out[43]: bar foo 1 4 2 5 3 6 In [44]: y Out[44]: bar foo 7 10 8 11 9 12

有一个很好的方法来获取以下DataFrame:

foo bar x 1 4 2 5 3 6 y 7 10 8 11 9 12

I have a dictionary of DataFrames, where the keys are assumed to be meaningful:

In [32]: x = pd.DataFrame(dict(foo=[1,2,3], bar=[4,5,6])).set_index('foo') In [33]: y = pd.DataFrame(dict(foo=[7,8,9], bar=[10,11,12])).set_index('foo') In [34]: z = dict(x=x, y=y)

Which looks like:

In [43]: x Out[43]: bar foo 1 4 2 5 3 6 In [44]: y Out[44]: bar foo 7 10 8 11 9 12

Is there a nice way to get the following DataFrame:

foo bar x 1 4 2 5 3 6 y 7 10 8 11 9 12

最满意答案

您可以使用concat ,字典的键将自动用于新的索引级别:

In [6]: z = dict(x=x, y=y) In [7]: pd.concat(z) Out[7]: bar foo x 1 4 2 5 3 6 y 7 10 8 11 9 12

您还可以使用concat的names参数为此新索引级别指定名称(例如names=['key'] )。

You can use concat for this, and the keys of the dictionary will automatically be used for a new index level:

In [6]: z = dict(x=x, y=y) In [7]: pd.concat(z) Out[7]: bar foo x 1 4 2 5 3 6 y 7 10 8 11 9 12

You can also give this new index level a name using the names argument of concat (eg names=['key']).