首页 > 解决方案 > 是否可以在 csv 文件中找到峰值并将峰值添加到同一 csv 文件的单独列中?(没有绘图)

问题描述

这是我的一段代码,但我不知道如何将此数组作为新列高度获取到格式的原始 csv 文件?

日期 等级 高度
01-01-2021 45 0
02-01-2021 43 0
03-01-2021 47 1
04-01-2021 46 0
......
import pandas as pd
from scipy.signal import find_peaks
import matplotlib.pyplot as plt

bestand = pd.read_csv('file.csv', skiprows=1, usecols=[0, 1] , names=['date', 'level'])
bestand = bestand['level']

indices = find_peaks(bestand, height= 37, threshold=None, distance=None)

height  = indices[1]['peak_heights']
print(height)

标签: pythonpandascsvscipy

解决方案


我想你想分配一个名为的列,该列在峰值height时取值为 1 。如果是这样:levelfind_peaks()

# Declare column full of zeros
bestand['height'] = 0
# Get row number of observations that are peaks
idx = find_peaks(x=bestand['level'], height=37)[0]
# Select rows in `idx` and replace their `height` with 1
bestand.iloc[idx, 2] = 1

这会返回:

         date  level  height
0  01-01-2021     45       0
1  02-01-2021     43       0
2  03-01-2021     47       1
3  04-01-2021     46       0

推荐阅读