2017-10-03 21 views
5

Tôi đã thấy một số bài viết về điều này nhưng tôi không thể có được đầu của tôi xung quanh cách hợp nhất, tham gia và concat sẽ đối phó với điều này. Làm thế nào tôi có thể hợp nhất hai dataframes để tìm các chỉ mục phù hợp?Kết hợp hai khung dữ liệu với nhiều chỉ mục

trong:

import pandas as pd 
import numpy as np 
row_x1 = ['a1','b1','c1'] 
row_x2 = ['a2','b2','c2'] 
row_x3 = ['a3','b3','c3'] 
row_x4 = ['a4','b4','c4'] 
index_arrays = [np.array(['first', 'first', 'second', 'second']), np.array(['one','two','one','two'])] 
df1 = pd.DataFrame([row_x1,row_x2,row_x3,row_x4], columns=list('ABC'), index=index_arrays) 
print(df1) 

ra:

   A B C 
first one a1 b1 c1 
     two a2 b2 c2 
second one a3 b3 c3 
     two a4 b4 c4 

trong:

row_y1 = ['d1','e1','f1'] 
row_y2 = ['d2','e2','f2'] 
df2 = pd.DataFrame([row_y1,row_y2], columns=list('DEF'), index=['first','second']) 
print(df2) 

ra

  D E F 
first d1 e1 f1 
second d2 e2 f2 

trong khác từ, làm thế nào tôi có thể hợp nhất chúng để đạt được df3 (như sau)?

trong

row_x1 = ['a1','b1','c1'] 
row_x2 = ['a2','b2','c2'] 
row_x3 = ['a3','b3','c3'] 
row_x4 = ['a4','b4','c4'] 
row_y1 = ['d1','e1','f1'] 
row_y2 = ['d2','e2','f2'] 

row_z1 = row_x1 + row_y1 
row_z2 = row_x2 + row_y1 
row_z3 = row_x3 + row_y2 
row_z4 = row_x4 + row_y2 

df3 = pd.DataFrame([row_z1,row_z2,row_z3,row_z4], columns=list('ABCDEF'), index=index_arrays) 
print(df3) 

ra

   A B C D E F 
first one a1 b1 c1 d1 e1 f1 
     two a2 b2 c2 d1 e1 f1 
second one a3 b3 c3 d2 e2 f2 
     two a4 b4 c4 d2 e2 f2 

Trả lời

6

Lựa chọn 1
Sử dụng pd.DataFrame.reindex + pd.DataFrame.join
reindexlevel tham số thuận tiện cho phép bạn mở rộng trên các chỉ số không có mặt.

df1.join(df2.reindex(df1.index, level=0)) 

      A B C D E F 
first one a1 b1 c1 d1 e1 f1 
     two a2 b2 c2 d1 e1 f1 
second one a3 b3 c3 d2 e2 f2 
     two a4 b4 c4 d2 e2 f2 

Lựa chọn 2
Bạn có thể đổi tên các trục của bạn và join sẽ làm việc

df1.rename_axis(['a', 'b']).join(df2.rename_axis('a')) 

      A B C D E F 
a  b       
first one a1 b1 c1 d1 e1 f1 
     two a2 b2 c2 d1 e1 f1 
second one a3 b3 c3 d2 e2 f2 
     two a4 b4 c4 d2 e2 f2 

Bạn có thể làm theo mà lên với rename_axis khác để có được kết quả mong muốn

df1.rename_axis(['a', 'b']).join(df2.rename_axis('a')).rename_axis([None, None]) 

      A B C D E F 
first one a1 b1 c1 d1 e1 f1 
     two a2 b2 c2 d1 e1 f1 
second one a3 b3 c3 d2 e2 f2 
     two a4 b4 c4 d2 e2 f2 

Các vấn đề liên quan