首页 > 解决方案 > 在 DataFrame 中插入新列与上一行的差异?

问题描述

我有一个带有数据集的 Pandas DataFrame,如下所示:

                           floor_temperature  power_consumption  outside_temperature
timestamp
2019-01-23 00:00:00+00:00           8.300000           0.022000           -11.393333
2019-01-23 00:10:00+00:00           8.114286           0.016000           -11.400000
2019-01-23 00:20:00+00:00           7.950000           0.044000           -11.254545
2019-01-23 00:30:00+00:00           7.900000           0.027500           -11.300000
2019-01-23 00:40:00+00:00           7.840000         830.900000           -11.400000
2019-01-23 00:50:00+00:00           8.300000         334.352000           -11.400000
2019-01-23 01:00:00+00:00           8.580000           0.028000           -11.380000
2019-01-23 01:10:00+00:00           8.440000           0.018000           -11.400000
2019-01-23 01:20:00+00:00           8.360000           0.022000           -11.400000

我想在“floor_temperatur”之后插入一个新行,它应该命名为“diff_floor_temperature”,并且应该通过将“floor_temperature”行减去前面的“floor_temperature”行来计算。

我知道使用 .diff() 函数应该很容易,但是在语法上提供一些帮助会很好。

标签: pythonpandas

解决方案


将 0x5453 的答案移至答案列,但更改了一些内容以确保不会出现任何切片错误。

df.loc[:,'diff_floor_temperature'] = df.loc[:,'floor_temperature'].diff()


推荐阅读