我在操作此表时遇到问题:
date time V_1 I_1 V_2 I_2 Temp
07.07.2017 12:36:27.801 0.000 0.532 0.001 1.289 25.655
07.07.2017 12:36:27.802 0.000 0.486 0.001 1.273 25.655
07.07.2017 12:36:27.803 0.000 0.482 0.001 1.322 25.655
07.07.2017 12:36:27.804 0.000 0.435 0.001 1.311 25.655
我需要每行之间的时间差(802-801 = 1ms),但我找不到任何解决方案来处理这个没有循环。 有没有更Pythonic的方法?
最佳答案
使用to_datetime
与 diff
然后得到 total_seconds
并乘以 1000
(ms
):
df['diff'] = pd.to_datetime(df['date'] + ' ' + df['time']).diff().dt.total_seconds() * 1000
print (df)
date time V_1 I_1 V_2 I_2 Temp diff
0 07.07.2017 12:36:27.801 0.0 0.532 0.001 1.289 25.655 NaN
1 07.07.2017 12:36:27.802 0.0 0.486 0.001 1.273 25.655 1.0
2 07.07.2017 12:36:27.803 0.0 0.482 0.001 1.322 25.655 1.0
3 07.07.2017 12:36:27.804 0.0 0.435 0.001 1.311 25.655 1.0
要将第一个值与列进行比较,请使用 sub
与 iat
选择列的第一个值:
df['diff'] = pd.to_datetime(df['date'] + ' ' + df['time'])
df['diff'] = df['diff'].sub(df['diff'].iat[0]).dt.total_seconds() * 1000
print (df)
date time V_1 I_1 V_2 I_2 Temp diff
0 07.07.2017 12:36:27.801 0.0 0.532 0.001 1.289 25.655 0.0
1 07.07.2017 12:36:27.802 0.0 0.486 0.001 1.273 25.655 1.0
2 07.07.2017 12:36:27.803 0.0 0.482 0.001 1.322 25.655 2.0
3 07.07.2017 12:36:27.804 0.0 0.435 0.001 1.311 25.655 3.0
关于python - 使用 Python pandas 进行数据操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45082924/