2017-05-10 67 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 
相關問題