【发布时间】:2021-09-14 18:34:52
【问题描述】:
假设我有一个像这样的数据框:
Col0 Col1 Col2 Col3 Col4
1.txt 2021-06-23 15:04:30 2021-06-23 14:10:30 2021-06-23 14:15:30 2021-06-23 14:20:30
2.txt 2021-06-23 14:25:30 2021-06-23 15:30:30 2021-06-23 14:35:30 2021-06-23 14:40:30
我想比较 Col1 中的时间戳是否大于 Col2 中的时间戳,如果是这样,我想从其他列(Col2、Col3、Col4)中删除时间戳。我还想检查 Col2 中的时间戳是否大于 Col3 中的时间戳,如果是这样,我想从其他列 Col3、Col4 中删除时间戳。
我试过这个:
df['Col1'] = pd.to_datetime(df['Col1'])
df['Col2'] = pd.to_datetime(df['Col2'])
df['Col3'] = pd.to_datetime(df['Col3'])
k= (df['Col1'] > df['Col2']).astype(int)
p=(df['Col2'] > df['Col3']).astype(int)
if k>0:
df['Col2']=np.nan
df['Col3']=np.nan
df['Col4']=np.nan
elif p>0:
df['Col3']=np.nan
df['Col4']=np.nan
但它向我显示了这个错误:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
我想要的输出如下所示:
Col0 Col1 Col2 Col3 Col4
1.txt 2021-06-23 15:04:30 NaN NaN NaN
2.txt 2021-06-23 14:25:30 2021-06-23 15:30:30 NaN NaN
编辑: 添加了 Col0
【问题讨论】:
标签: python python-3.x pandas dataframe timestamp