pandas 用 0 天替换 NaT
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49240881/
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
replacing NaT with 0 days
提问by Number Logic
I have a pandas dataframe that looks lie:
我有一个看起来撒谎的Pandas数据框:
A
3 days
NaT
4 days
Is there a way to replace the NaT with 0 days ?
有没有办法用 0 days 替换 NaT ?
thanks, Ed
谢谢,埃德
回答by manoj
Another way will be to use .replace
另一种方法是使用 .replace
d = {'A': ['3 days', '4 days', 'NaT']}
df = pd.DataFrame(data=d)
df.replace({'NaT': '0 day'}, inplace=True)
Output:
输出:
A
0 3 days
1 4 days
2 0 day
回答by Simon
Please note that the other answers are not up to date anymore. The preferred syntax is:
请注意,其他答案不再是最新的。首选语法是:
df['column'].fillna(pd.Timedelta(seconds=0))
The previously mentioned
前面提到的
df['column'].fillna(0)
will results in:
将导致:
FutureWarning: Passing integers to fillna is deprecated, will raise a TypeError in a future version. To retain the old behavior, pass pd.Timedelta(seconds=n) instead. df['column'] = df['column'].fillna(0)
FutureWarning:不推荐将整数传递给 fillna,将在未来版本中引发 TypeError。要保留旧行为,请改为传递 pd.Timedelta(seconds=n)。df['column'] = df['column'].fillna(0)
回答by piRSquared
df.A = pd.to_timedelta(df.A)
df.fillna(0)
A
0 3 days
1 0 days
2 4 days
回答by KC54
When trying to implement manoj's replace-based answer with version 0.24.1, I found that I had to use "pandas.NaT" rather than just the string "Nat":
在尝试使用版本 0.24.1 实现 manoj 基于替换的答案时,我发现我必须使用“pandas.NaT”而不仅仅是字符串“Nat”:
import pandas as pd
...
df.replace({pd.NaT: "0 days"}, inplace=True)