2つのデータフレームをマージし、名前で列レベルを追加する


9

こんにちは私はパンダのconcat、join、mergeメソッドを掘り下げてきましたが、必要なものが見つからないようです。

2つのデータフレームがあるとしましょう

A = pd.DataFrame("A",index=[0,1,2,3,4],columns=['Col 1','Col 2','Col 3'])
B = pd.DataFrame("B",index=[0,1,2,3,4],columns=['Col 1','Col 2','Col 3'])
>>> A
  Col 1 Col 2 Col 3
0     A     A     A
1     A     A     A
2     A     A     A
3     A     A     A
4     A     A     A
>>> B
  Col 1 Col 2 Col 3
0     B     B     B
1     B     B     B
2     B     B     B
3     B     B     B
4     B     B     B

列をマージして新しいデータフレームを作成したいのですが、列をどのようにしたいかについてマルチインデックスを作成すると、最も簡単に説明できます

index = pd.MultiIndex.from_product([A.columns.values,['A','B']])
>>> index
MultiIndex(levels=[['Col 1', 'Col 2', 'Col 3'], ['A', 'B']],
           labels=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]])

列のこのマルチインデックスで空のデータフレームを作成すると

empty_df = pd.DataFrame('-',index=A.index,columns=index)
>>> empty_df
  Col 1    Col 2    Col 3
      A  B     A  B     A  B
0     -  -     -  -     -  -
1     -  -     -  -     -  -
2     -  -     -  -     -  -
3     -  -     -  -     -  -
4     -  -     -  -     -  -

私の質問は、それを取得するためにどのマージ、連結、または結合を使用するのですか?私は、concat ... inner、outerなどについて複数のことを試しました。欲しいものが見つからないようです。私が考えることができる唯一のことは、空のデータフレームを作成し、次に埋め戻すことです。

編集:エズラエルの反応を試した後、それは近いですが、正確ではありません。入れ子になった種類の列のようなものですか?例えば

empty_df['Col 1']
>>> empty_df['Col 1']
   A  B
0  -  -
1  -  -
2  -  -
3  -  -
4  -  -

または

>>> empty_df['Col 1']['A']
0    -
1    -
2    -
3    -
4    -
Name: A, dtype: object

だからこれは私が思いついた解決策ですが、それは列を反復することからです。

row_idx = A.index.union(B.index)
col_idx = pd.MultiIndex.from_product([A.columns.values,['A','B']])
new_df = pd.DataFrame('-',index=row_idx,columns=col_idx)
for column in A.columns:
   new_df.loc[:,(column,'A')] = A[column]
   new_df.loc[:,(column,'B')] = B[column]
>>> new_df
  Col 1    Col 2    Col 3
      A  B     A  B     A  B
0     A  B     A  B     A  B
1     A  B     A  B     A  B
2     A  B     A  B     A  B
3     A  B     A  B     A  B
4     A  B     A  B     A  B
>>> new_df['Col 1']
   A  B
0  A  B
1  A  B
2  A  B
3  A  B
4  A  B
>>> new_df['Col 1']['A']
0    A
1    A
2    A
3    A
4    A
Name: A, dtype: object

回答:


8

私はあなたが必要だと思うconcatkeys、パラメータとaxis=1、最後の変更により、レベルの順序DataFrame.swaplevelとすることにより、第1のレベルによってソートDataFrame.sort_index

df1 = (pd.concat([A, B], axis=1, keys=('A','B'))
         .swaplevel(0,1, axis=1)
         .sort_index(axis=1, level=0))
print (df1)
  Col 1    Col 2    Col 3   
      A  B     A  B     A  B
0     A  B     A  B     A  B
1     A  B     A  B     A  B
2     A  B     A  B     A  B
3     A  B     A  B     A  B
4     A  B     A  B     A  B

での作業MultiIndexは可能DataFrame.xsです:

print (df1.xs('Col 1', axis=1, level=0))
   A  B
0  A  B
1  A  B
2  A  B
3  A  B
4  A  B

MultiIndex column使用を選択したい場合tuple

print (df1[('Col 1', 'A')])
0    A
1    A
2    A
3    A
4    A
Name: (Col 1, A), dtype: object

インデックスと列を使用して選択する場合loc

print (df1.loc[4, ('Col 1', 'A')])
A

2
やった!どうもありがとうございました!
Melendowski、
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.