pandas to_datetime()然后在DateTime Index上使用concat()

时间:2017-05-10 15:35:04

标签: python pandas datetime

我尝试使用concat在其日期时间索引上合并2个数据框,但它没有像我预期的那样工作。我为此示例复制了documentation中示例中的部分代码:

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 个答案:

答案 0 :(得分:3)

传递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)

您需要axis = 1:

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

输出:

            value    0
2015-02-04    444  222
2016-03-05    555  333