複数のPandas DataFramesを連結しようとしていますが、そのうちのいくつかはマルチインデックスを使用し、他のものは単一インデックスを使用しています。マルチインデックスのデータフレームとともにシングルとマルチインデックスPandas DataFramesの組み合わせ方法
> 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
は今、私は2つのデータフレームを連結したいです。私は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