python - 如何在 DataFrame 中创建显示最后记录峰值的列?

标签 python pandas scipy

我正在尝试创建一个新列来列出最后记录的峰值,直到下一个峰值出现。例如,假设这是我现有的 DataFrame:

index values
0      10
1      20
2      15
3      17
4      15
5      22
6      20

我想得到这样的东西:

index values last_recorded_peak
0      10        10
1      20        20
2      15        20
3      17        17
4      15        17
5      22        22
6      20        22

到目前为止,我已尝试使用 np.maximum.accumulate,它“累积”最大值但不完全是“峰值”(某些峰值可能低于最大值)。

我也尝试过使用 scipy.signal.find_peaks 返回我的峰值所在的索引数组(在示例中,索引 1、3、5),这不是我要找的。

我对编码比较陌生,非常感谢任何指点!

最佳答案

你在正确的轨道上,scipy.signal.find_peaks是我要走的路,你只需要根据结果做一点工作:

from scipy import signal
peaks = signal.find_peaks(df['values'])[0]

df['last_recorded_peak'] = (df.assign(last_recorded_peak=float('nan'))
                              .last_recorded_peak
                              .combine_first(df.loc[peaks,'values'])
                              .ffill()
                              .combine_first(df['values']))

print(df)

     index  values  last_recorded_peak
0      0      10                10.0
1      1      20                20.0
2      2      15                20.0
3      3      17                17.0
4      4      15                17.0
5      5      22                22.0
6      6      20                22.0

关于python - 如何在 DataFrame 中创建显示最后记录峰值的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57655315/

相关文章:

python - Pandas read_sql() - AttributeError : 'Engine' object has no attribute 'cursor'

python - 在我的代码中使用 python 字 "type"是否安全?

python - 大型 3D 阵列上的快速一维线性 np.NaN 插值

python - 复杂数据的曲线拟合

python - 设计启发式方法来编写与 `scipy.integrate.odeint` 交互的 Python 类?

python - 快速读取Python中的列分隔文本数据

Python ascii utf unicode

python - Pandas 删除列多索引中的空白行

python - 在 python pandas 中删除行

python - 将数据帧按特定列压缩为包含第一个和最后一个时间戳以及值平均值的行