pandas to_datetime() then concat() on DateTime Index
datetime, pandas, python
Solution
pass `axis=1` to concatenate column-wise:
In [7]:
pd.concat([df,df2], axis=1)
Out[7]:
value 0
2015-02-04 444 222
2016-03-05 555 333
Alternatively you could've `join`ed:
In [5]:
df.join(df2)
Out[5]:
value 0
2015-02-04 444 222
2016-03-05 555 333
or `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
Problem
I'm trying to merge 2 DataFrames using `concat`, on their DateTime Index, but it's not working as I expected. I copied some of this code from the example in the documentation for this example: ``` 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 ``` Why isn't it recognizing the same dates on the index and merging accordingly? I verified that both Indexes are 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) ``` Thanks.