【问题标题】:How to correctly use fillna() for a datetime column in pandas dataframe (not working)?如何正确使用 fillna() 作为 pandas 数据框中的日期时间列(不起作用)?
【发布时间】:2017-02-17 10:39:46
【问题描述】:

我有一个如下图所示的数据框:

       Age  CreatedDate   TestDate               Performance
544    51   2015-11-23    2015-12-11                   1
325    51   2015-11-23    2016-01-04                   0
1043   51   2016-01-26    2016-01-25                   1
303    51   2016-01-26    2016-02-15                   1
1076   50   2015-04-29           NaT                   0

我想用创建日期的数据更新我的值为 NaT 的 TestDate,如下所示:

       Age  CreatedDate   TestDate               Performance
544    51   2015-11-23    2015-12-11                   1
325    51   2015-11-23    2016-01-04                   0
1043   51   2016-01-26    2016-01-25                   1
303    51   2016-01-26    2016-02-15                   1
1076   50   2015-04-29    2015-04-29                   0

我尝试使用方法 fillna(),但是,虽然没有发出错误,但我的数据没有被更新。

df['TestDate'].fillna(pd.to_datetime(df['CreatedDate']))

有什么建议吗? 之前谢谢。

【问题讨论】:

    标签: python python-3.x pandas datetime


    【解决方案1】:

    在填写 NaT 之前,您应该将日期时间列 TestDateCreatedDate 转换为 datetime 格式:

    df['TestDate'] = pd.to_datetime(df['TestDate'])
    
    df['CreatedDate'] = pd.to_datetime(df['CreatedDate'])
    

    然后记得在您的声明中添加inplace=True

    In [20]: df['TestDate'].fillna(df['CreatedDate'], inplace=True)
    
    In [21]: df
    Out[21]: 
          Age CreatedDate   TestDate  Performance
    544    51  2015-11-23 2015-12-11            1
    325    51  2015-11-23 2016-01-04            0
    1043   51  2016-01-26 2016-01-25            1
    303    51  2016-01-26 2016-02-15            1
    1076   50  2015-04-29 2015-04-29            0
    

    检查数据类型:

    In [22]: df.dtypes
    Out[22]: 
    Age                     int64
    CreatedDate    datetime64[ns]
    TestDate       datetime64[ns]
    Performance             int64
    dtype: object
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-14
      • 2017-01-04
      • 2021-05-27
      • 1970-01-01
      • 1970-01-01
      • 2015-01-17
      • 2021-06-04
      • 2020-08-18
      相关资源
      最近更新 更多