![](/img/trans.png)
[英]python/pandas: how to combine two dataframes into one with hierarchical column index?
[英]Python pandas: Combine two dataframes by date index and a common column value
有兩個日期幀,一個是df1,另一個是df2,如下所示:
DF1:
a b id
2010-01-01 1 4 21
2010-01-01 2 5 22
2010-01-01 3 6 23
2010-01-01 4 7 24
2010-01-02 1 4 21
2010-01-02 2 5 22
2010-01-02 3 6 23
2010-01-02 4 7 24
2010-01-03 1 4 21
2010-01-03 2 5 22
2010-01-03 3 6 23
2010-01-03 4 7 24
...........................
DF2:
c d id
2010-01-02 1 4 21
2010-01-02 2 5 22
2010-01-02 3 6 23
2010-01-02 4 7 24
2010-01-03 1 4 21
2010-01-03 2 5 22
2010-01-03 3 6 23
2010-01-03 4 7 24
...........................
我想通過公共索引合並或連接兩個數據幀(請注意df1中的某些索引不在df2中)和id,我期望一個連接的數據幀如下
c d a b id
2010-01-02 1 4 1 4 21
2010-01-02 2 5 2 5 22
2010-01-02 3 6 3 6 23
2010-01-02 4 7 4 7 24
2010-01-03 1 4 1 4 21
2010-01-03 2 5 2 5 22
2010-01-03 3 6 3 6 23
2010-01-03 4 7 4 7 24
我使用了以下代碼
df = df1.join(df2, on = ['id'], how='inner')
但那沒用
IIUC:
In [388]: df2.set_index('id', append=True).join(df1.set_index('id', append=True)) \
.reset_index(level='id')
Out[388]:
id c d a b
2010-01-02 21 1 4 1 4
2010-01-02 22 2 5 2 5
2010-01-02 23 3 6 3 6
2010-01-02 24 4 7 4 7
2010-01-03 21 1 4 1 4
2010-01-03 22 2 5 2 5
2010-01-03 23 3 6 3 6
2010-01-03 24 4 7 4 7
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.