如果其他列中的行匹配,则计算pandas中的时间差(以秒为单位)

izkcnapc  于 2023-05-21  发布在  其他
关注(0)|答案(1)|浏览(149)

我在一个pandas DataFrame中处理3列('time','SEC','DeviceName')。我使用下面的代码来计算'time'列中的行之间的差异,并分配给'SEC'列:

df['SEC'] = df['time'].diff().dt.total_seconds()

“DeviceName”列可以有几个不同的设备,因此我需要修改它,以便仅在设备名称与前一行匹配时才执行计算,否则将0分配给“SEC”。
例如:

time                    SEC       DeviceName
4/18/2023 2:43:00                 Applied_AA-12
4/18/2023 3:13:00       1800      Applied_AA-12  # calculate because the device name matches the previous row
4/18/2023 3:35:53       0         Applied_AA-14  # don't calculate because the device name doesn't match the previous row
4/18/2023 3:36:03       10        Applied_AA-14  # calculate because the device name matches the previous row
uyto3xhc

uyto3xhc1#

可以使用GroupyBy.diff

df["SEC"] = df.groupby("DeviceName")["time"].diff().dt.total_seconds().fillna(0)

df.at[0, "SEC"] = np.nan # is this optional ?

输出:

print(df)

                 time     DeviceName     SEC
0 2023-04-18 02:43:00  Applied_AA-12     NaN
1 2023-04-18 03:13:00  Applied_AA-12 1800.00
2 2023-04-18 03:35:53  Applied_AA-14    0.00
3 2023-04-18 03:36:03  Applied_AA-14   10.00

相关问题