日期时间对象上的 Pandas fillna
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21145015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas fillna on datetime object
提问by Luke
I'm trying to run fillnaon a column of type datetime64[ns]. When I run something like:
df['date'].fillna(datetime("2000-01-01"))
我正在尝试fillna在 datetime64[ns] 类型的列上运行。当我运行类似的东西时:
df['date'].fillna(datetime("2000-01-01"))
I get:
TypeError: an integer is required
我得到:
TypeError: an integer is required
Any way around this?
有什么办法解决这个问题吗?
回答by Jeff
This should work in 0.12 and 0.13 (just released).
这应该适用于 0.12 和 0.13(刚刚发布)。
@DSM points out that datetimes are constructed like: datetime.datetime(2012,1,1)SO the error is from failing to construct the value the you are passing to fillna.
Note that using a TimestampWILL parse the string.
@DSM 指出日期时间的构造如下:datetime.datetime(2012,1,1)所以错误是由于未能构造您传递给的值fillna。请注意,使用TimestampWILL 解析字符串。
In [3]: s = Series(date_range('20130101',periods=10))
In [4]: s.iloc[3] = pd.NaT
In [5]: s.iloc[7] = pd.NaT
In [6]: s
Out[6]:
0 2013-01-01 00:00:00
1 2013-01-02 00:00:00
2 2013-01-03 00:00:00
3 NaT
4 2013-01-05 00:00:00
5 2013-01-06 00:00:00
6 2013-01-07 00:00:00
7 NaT
8 2013-01-09 00:00:00
9 2013-01-10 00:00:00
dtype: datetime64[ns]
datetime.datetimewill work as well
datetime.datetime也能用
In [7]: s.fillna(Timestamp('20120101'))
Out[7]:
0 2013-01-01 00:00:00
1 2013-01-02 00:00:00
2 2013-01-03 00:00:00
3 2012-01-01 00:00:00
4 2013-01-05 00:00:00
5 2013-01-06 00:00:00
6 2013-01-07 00:00:00
7 2012-01-01 00:00:00
8 2013-01-09 00:00:00
9 2013-01-10 00:00:00
dtype: datetime64[ns]
回答by Niklavr
This example is works with dynamic data if you want to replace NaTdata in rows with data from another DateTime data.
如果您想NaT用来自另一个 DateTime 数据的数据替换行中的数据,则此示例适用于动态数据。
df['column_with_NaT'].fillna(df['dt_column_with_thesame_index'], inplace=True)
It's works for me when I was updated some rows in DateTime column and not updated rows had NaT value, and I've been needed to inherit old series data. And this code above resolve my problem. Sry for the not perfect English )
当我更新 DateTime 列中的某些行并且未更新的行具有 NaT 值时,它对我有用,并且我需要继承旧的系列数据。上面的代码解决了我的问题。Sry 不完美的英语)

