比较熊猫中包含时间戳的两列

时间:2021-07-02 21:27:38

标签: python python-3.x pandas dataframe timestamp

假设我有一个这样的数据框:

  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

2 个答案:

答案 0 :(得分:1)

使用布尔掩码的简单方法:

dt = df.select_dtypes('datetime')
dt = dt.mask(dt.lt(dt.shift(axis=1)).cumsum(axis=1).astype(bool))

df.loc[:, dt.columns.tolist()] = dt
>>> df
    Col0                Col1                Col2 Col3 Col4
0  1.txt 2021-06-23 15:04:30                 NaT  NaT  NaT
1  2.txt 2021-06-23 14:25:30 2021-06-23 15:30:30  NaT  NaT

答案 1 :(得分:0)

我尝试了这个并得到了我想要的输出(当数据框还包含其他带有“str”和“float”的列时):

df['Col1'] = pd.to_datetime(df['Col1'])
df['Col2'] = pd.to_datetime(df['Col2'])
df['Col3'] = pd.to_datetime(df['Col3'])
df.loc[df['Col1'] > df['Col2'], 'Col2'] = np.nan
df.loc[df['Col1'] > df['Col2'], 'Col3'] = np.nan
df.loc[df['Col1'] > df['Col2'], 'Col4'] = np.nan


df.loc[df['Col2'] > df['Col3'], 'Col3'] = np.nan
df.loc[df['Col2'] > df['Col3'], 'Col4'] = np.nan