python - 使用 Python pandas 进行数据操作

标签 python pandas datetime time

我在操作此表时遇到问题:

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_datetimediff然后得到 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

要将第一个值与列进行比较,请使用 subiat选择列的第一个值:

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/

相关文章:

python - Django1.5 - python2.7 -如何显示和更新具有3个外键的数据库

reactjs - 更改日期时间字段以返回 django rest 框架中的 unix 时间戳

javascript - 如何仅显示日期时间(分和秒)

Python - 算法查找时隙

python - Pandas:如何包含多个数据透视表的所有列和所有索引

python - 使用 Python 将字符串标记为嵌套数组列表

python - 属性错误: 'Series' object has no attribute 'columns'

python - Pandas 哈希表 KeyError

python - 从数据框中删除重复项,基于两列 A,B,在另一列 C 中保持具有最大值的行

python - ImportError : No module named google. protobuf