首页 > 解决方案 > 加入索引和列

问题描述

我想根据两个条件加入两个数据框: 1. 通过索引加入 2. 如果两个列标题都在两个数据框中,也加入它们

举个例子,假设我有这两个数据框:

import pandas as pd
import numpy as np

df1 = pd.DataFrame({'date': [2010, 2011, 2012],
               'a': [np.NaN, 30, np.NaN],
               'b': [55, np.NaN, np.NaN],
               'c': [55, 40, 84]})
df1 = df1.set_index("date")

df2 = pd.DataFrame({'date': [2010, 2011, 2012],
               'a': [10, np.NaN, 30],
               'b': [np.NaN, 80, 84],
               'd': [55, 40, 84]})
df2 = df2.set_index("date")

如果我现在通过 pd.concat 加入这两者,我会两次获得诸如“a”之类的列:

pd.concat([df1, df2], axis=1) 

         a      b      c    a       b       d
date                        
2010    NaN     55.0   55   10.0    NaN     55
2011    30.0    NaN    40   NaN     80.0    40
2012    NaN     NaN    84   30.0    84.0    84

但我宁愿有:

         a      b      c     d
date                        
2010    10.0    55.0   55    55
2011    30.0    80.0   40    40
2012    30.0    84.0   84    84

提前致谢!

标签: pythondataframejoin

解决方案


试试这个,添加

print(df1.set_index('date').add(df2.set_index("date"), fill_value=0))

         a     b     c     d
date                        
2010  10.0  55.0  55.0  55.0
2011  30.0  80.0  40.0  40.0
2012  30.0  84.0  84.0  84.0

推荐阅读