2017-05-10 66 views
2

我试图合并使用concat,在他们的日期时间索引上的2个数据帧,但它不像我预期的那样工作。我复制了一些这个代码的例子在documentation对于本例:熊猫to_datetime()然后concat()日期时间索引

import pandas as pd 

df = pd.DataFrame({'year': [2015, 2016], 
        'month': [2, 3], 
        'day': [4, 5], 
        'value': [444,555]}) 

df.set_index(pd.to_datetime(df.loc[:,['year','month','day']]),inplace=True) 

df.drop(['year','month','day'],axis=1,inplace=True) 

df2 = pd.DataFrame(data=[222,333], 
        index=pd.to_datetime(['2015-02-04','2016-03-05'])) 

pd.concat([df,df2]) 
Out[1]: 
      value  0 
2015-02-04 444.0 NaN 
2016-03-05 555.0 NaN 
2015-02-04 NaN 222.0 
2016-03-05 NaN 333.0 

为什么是不是认识上的索引相同的日期,因此合并?我确认这两个索引都是DateTime:

df.index 
Out[2]: DatetimeIndex(['2015-02-04', '2016-03-05'], dtype='datetime64[ns]', freq=None) 

df2.index 
Out[3]: DatetimeIndex(['2015-02-04', '2016-03-05'], dtype='datetime64[ns]', freq=None) 

谢谢。

回答

2

axis=1来连接逐列:

In [7]: 
pd.concat([df,df2], axis=1) 

Out[7]: 
      value 0 
2015-02-04 444 222 
2016-03-05 555 333 

或者你可能已经join编辑:

In [5]: 
df.join(df2) 

Out[5]: 
      value 0 
2015-02-04 444 222 
2016-03-05 555 333 

merge d:

In [8]: 
df.merge(df2, left_index=True, right_index=True) 

Out[8]: 
      value 0 
2015-02-04 444 222 
2016-03-05 555 333 
1

你需要轴= 1 :

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

输出:

  value 0 
2015-02-04 444 222 
2016-03-05 555 333 
相关问题