我正在尝试将熊猫数据帧中的 NaT 值替换为 NaN,如下所示
df = df.replace([pd._libs.tslibs.nattype.NaTType], np.nan)
但后来我检查回来了
print(df["col"])
print(type(df["col"][0]))
print(isinstance(df["col"][0], pd._libs.tslibs.nattype.NaTType))
并得到
0 NaT
1 NaT
2 NaT
3 NaT
4 NaT
..
1123568 NaT
1123569 NaT
1123570 NaT
1123571 NaT
1123572 NaT
Name: col, Length: 1123573, dtype: datetime64[ns]
<class 'pandas._libs.tslibs.nattype.NaTType'>
True
谢谢!
更好的问题是为什么 dtype 与日期/时间相关联。 列中是否有日期/时间的值?
s='''value time
1 NaT
2 NaT'''
df = pd.read_csv(io.StringIO(s), sep='s+', converters={'time': pd.to_datetime})
df['time'] = df['time'].fillna(pd.Timedelta(seconds=0).seconds).replace({0: pd.np.nan})
print(df)
value time
0 1 NaN
1 2 NaN
不知道为什么这不起作用。df = df.replace(pd.NaT, np.NaN)
或df.replace(pd.NaT, np.NaN, inplace=True)
这将起作用,但并非所有情况都是最好的......
def apply_nat_replacer(x):
x = str(x)
if x == 'NaT':
x = 'nat_replaced'
else:
x =x
return x
df[1] = df.apply(lambda row: apply_nat_replacer(row[1]), axis=1)