简体   繁体   English

如何正确使用fillna()作为熊猫数据框中的日期时间列(不起作用)?

[英]How to correctly use fillna() for a datetime column in pandas dataframe (not working)?

I have a dataframe as shown below: 我有一个数据框,如下所示:

       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

I want to update my TestDate which has value of NaT with the data from Created date, as such: 我想用来自创建日期的数据更新具有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

I've tried to use the method fillna(), however, my data is not being updated though there is no error emitted. 我尝试使用方法fillna(),尽管没有发出错误,但我的数据没有更新。

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

Any advice? 有什么建议吗? Thanks Before. 谢谢之前。

You should convert your datetime columns TestDate and CreatedDate into datetime format before filling NaT : 在填充NaT之前,应将datetime列TestDateCreatedDate转换为datetime格式:

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

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

then remember to add inplace=True to your statement: 然后记住在您的声明中添加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

Checking dtypes: 检查dtype:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM