在尝试获取timedelta对象天时,pandas用列中的字符串替换NaT

时间:2018-01-30 11:36:46

标签: python python-3.x pandas dataframe

我有以下df

A         B
3 days    NaT
NaT       1 days
4 days    3 days
NaT       NaT

dtype AB的{​​{1}}为timedelta64[ns],我想从两列days中获取timedelta,首先,我尝试删除A的所有行,而B恰好是NaT

daydelta = df.dropna(subset=['A', 'B'], how='all')

然后在每个列值

上获取days
daydelta[['A', 'B']] = daydelta[['A', 'B']].applymap(lambda x: int(Timedelta(x).days))

但由于days中没有NaT属性,因此失败了。我想知道如何从days值获取timedelta,同时用字符NaT替换timedelta value does not exist

1 个答案:

答案 0 :(得分:1)

使用与NaT合作的dt.days

print (df['A'].dt.days)
0    3.0
1    NaN
2    4.0
3    NaN
Name: A, dtype: float64

df[['A', 'B']] = df[['A', 'B']].apply(lambda x: x.dt.days)
print (df)
     A    B
0  3.0  NaN
1  NaN  1.0
2  4.0  3.0
3  NaN  NaN