如何合并具有相同列名的pandas DataFrame?

时间:2018-06-12 19:39:12

标签: python pandas

索引是时间戳和列名,也是将NaN替换为值的功能。它似乎没有工作。

样品:

import pandas as pd

times = pd.to_datetime(pd.Series(['2014-07-4',
'2014-07-15','2014-08-24','2014-08-25','2014-09-10','2014-09-17']))
valuea = [0.01, 0.02, -0.03, 0.4 ,0.5,np.NaN]

times2 = pd.to_datetime(pd.Series(['2014-07-6',
'2014-07-16','2014-08-27','2014-09-5','2014-09-11','2014-09-17']))
valuea2 = [1, 2, 3, 4,5,-6]


df1 = pd.DataFrame({'value A': valuea}, index=times)
df2 = pd.DataFrame({'value A': valuea2}, index=times2)

df3=pd.merge(df1,df2, left_index=True, right_index=True)
df3.head()

1 个答案:

答案 0 :(得分:1)

假设您需要外部联接

pd.concat([df1,df2],axis=1)
Out[321]: 
            value A  value A
2014-07-04     0.01      NaN
2014-07-06      NaN      1.0
2014-07-15     0.02      NaN
2014-07-16      NaN      2.0
2014-08-24    -0.03      NaN
2014-08-25     0.40      NaN
2014-08-27      NaN      3.0
2014-09-05      NaN      4.0
2014-09-10     0.50      NaN
2014-09-11      NaN      5.0
2014-09-17      NaN     -6.0

更新

df1.combine_first(df2)
Out[324]: 
            value A
2014-07-04     0.01
2014-07-06     1.00
2014-07-15     0.02
2014-07-16     2.00
2014-08-24    -0.03
2014-08-25     0.40
2014-08-27     3.00
2014-09-05     4.00
2014-09-10     0.50
2014-09-11     5.00
2014-09-17    -6.00