【问题标题】:pandas to_datetime() then concat() on DateTime Indexpandas to_datetime() 然后在 DateTime 索引上 concat()
【发布时间】:2017-05-10 15:35:03
【问题描述】:

我正在尝试使用 concat 在它们的 DateTime 索引上合并 2 个 DataFrame,但它没有按我预期的那样工作。我从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

为什么它不能识别索引上的相同日期并相应地合并?我验证了两个索引都是日期时间:

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)

谢谢。

【问题讨论】:

    标签: python pandas datetime


    【解决方案1】:

    传递axis=1 以逐列连接:

    In [7]:
    pd.concat([df,df2], axis=1)
    
    Out[7]:
                value    0
    2015-02-04    444  222
    2016-03-05    555  333
    

    您也可以joined:

    In [5]:
    df.join(df2)
    
    Out[5]:
                value    0
    2015-02-04    444  222
    2016-03-05    555  333
    

    merged:

    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
    

    【讨论】:

      【解决方案2】:

      你需要axis=1:

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

      输出:

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

      【讨论】:

        猜你喜欢
        • 2016-08-23
        • 1970-01-01
        • 1970-01-01
        • 2017-02-01
        • 2018-10-07
        • 2020-08-01
        • 2016-12-23
        • 2018-08-27
        • 2018-04-22
        相关资源
        最近更新 更多