我想连接多个熊猫数据帧,其中一些使用多索引,其他使用单索引。作为一个例子,让我们考虑以下单索引的数据帧:如何结合单索引和多索引熊猫数据帧
> import pandas as pd
> df1 = pd.DataFrame({'single': [10,11,12]})
> df1
single
0 10
1 11
2 12
随着一个多指标数据帧:
> level_dict = {}
> level_dict[('level 1','a','h')] = [1,2,3]
> level_dict[('level 1','b','j')] = [5,6,7]
> level_dict[('level 2','c','k')] = [10, 11, 12]
> level_dict[('level 2','d','l')] = [20, 21, 22]
> df2 = pd.DataFrame(level_dict)
> df2
level 1 level 2
a b c d
h j k l
0 1 5 10 20
1 2 6 11 21
2 3 7 12 22
现在我想将两者连接起来dataframes。当我尝试使用concat
它展平了多指标如下:
> df3 = pd.concat([df2,df1], axis=1)
> df3
(level 1, a, h) (level 1, b, j) (level 2, c, k) (level 2, d, l) single
0 1 5 10 20 10
1 2 6 11 21 11
2 3 7 12 22 12
相反,如果我一列追加到多指标数据帧df2
如下:
> df2['single'] = [10,11,12]
> df2
level 1 level 2 single
a b c d
h j k l
0 1 5 10 20 10
1 2 6 11 21 11
2 3 7 12 22 12
我怎么能代替生成该数据帧df1
和df2
与concat
,merge
或join
?
谢谢@chrisb!我曾希望有一种更简单更通用的方法,但我能够在这里制定解决方案以满足我的需求 – wbinventor