簡體   English   中英

熊貓中兩個數據框的簡單連接

[英]Simple join of two Data Frames in Pandas

我在使用Pandas的Python程序中有兩個數據框。 我是熊貓新手。

每個都有許多列和行-第一個類似於:

   calc_1  calc_2 calc_3
0  34.3   43.1  42.0
2  3.0    4.0   5.0
3  6.1    6.1   6.2
4  4.2    4.3   4.5

第二個類似於:

   gender  age 
0  M      25
2  M      27
3  M      27
4  F      36

對於每個整數行索引,第二個數據幀中都有一個對應的條目。 我想將它們連接到行索引相等的結果數據框中,例如SQL中的內部連接。

我似乎無法正確理解。 追加結果是我應具有的行數的2倍。 該信息來自CSV。

   calc_1  calc_2 calc_3  gender age
0  34.3   43.1  42.0      M      25
2  3.0    4.0   5.0       M      27
3  6.1    6.1   6.2       M      27
4  4.2    4.3   4.5       F      36

我想在加入時保留列順序。

編輯:

我似乎無法使用合並,因為整數索引沒有名稱

 pd.merge(df1, df2, on='?????', how='inner')

使用pd.concat並傳遞axis=1來按列連接:

In [37]:

pd.concat([df,df1], axis=1)
Out[37]:
   calc_1  calc_2  calc_3 gender  age
0    34.3    43.1    42.0      M   25
2     3.0     4.0     5.0      M   27
3     6.1     6.1     6.2      M   27
4     4.2     4.3     4.5      F   36

join

In [38]:

df.join(df1)
Out[38]:
   calc_1  calc_2  calc_3 gender  age
0    34.3    43.1    42.0      M   25
2     3.0     4.0     5.0      M   27
3     6.1     6.1     6.2      M   27
4     4.2     4.3     4.5      F   36

merge並設置left_index=Trueright_index=True

In [41]:

df.merge(df1, left_index=True, right_index=True)
Out[41]:
   calc_1  calc_2  calc_3 gender  age
0    34.3    43.1    42.0      M   25
2     3.0     4.0     5.0      M   27
3     6.1     6.1     6.2      M   27
4     4.2     4.3     4.5      F   36

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM