我得到了这一系列带有索引的数据点;所以数据框看起来像这样:
index value
0 3.075
1 44.338
2 10.030
然后我写了一个函数,get_extrema,它找到所有局部极值并返回一个包含 3 列的数据帧:index、value、 类型。
index = the index of the extrema in the original given data set
value = the value of the local extrema found
type = either 'max' or 'min'
然后,使用 get_extrema 的结果,我编写了另一个函数来查找极值对的振幅(也就是局部最小值和局部最大值之间的值差)...我d 只喜欢返回振幅最大的顶部对:
def get_amplitude(extremas, col, n):
amps = abs(extremas[col].diff(periods=1))
amps.sort_values(inplace=True, ascending=False)
amps = amps.head(n)
df = pd.DataFrame({'local minima': extremas.loc[amps.index, 'value'],
'local maxima': extremas.loc[amps.index - 1, 'value']})
return df
Extremas 是 get_extremas 输出的数据帧,col 是所提及数据帧中包含极值的列的名称,n 是前 n 对之间差异最大的数局部最小/最大对。
它工作正常,但答案输出有点奇怪:
+-------------------------------------+
| | local maxima | local minima |
+-------+--------------+--------------+
| 17398 | 433.75 | NaN |
| 17399 | NaN | -99.00 |
| 17551 | 438.00 | NaN |
| 17552 | NaN | -88.25 |
| 21262 | 437.75 | NaN |
| 21263 | NaN | -120.75 |
+-------+--------------+--------------+
我想要的输出:
+-------------------------------------+
| | local maxima | local minima |
+-------+--------------+--------------+
| 0 | 433.75 | -99.00 |
| 1 | 438.00 | -88.25 |
| 2 | 437.75 | -120.75 |
+-------+--------------+--------------+
我知道我的输出格式是由于我尝试合并的两个数据帧具有不同的索引。但我该如何克服呢?
我不能使用 df.merge(df2) 因为它们不共享相同的 key 。
我觉得一定有一个非常简单的解决方案被我忽略了。感谢您的帮助!
请您参考如下方法:
这对您的案子有帮助吗?我不确定我们是否在同一页面上,但我认为这就是您要尝试做的 -
import pandas as pd
import numpy as np
# create random data
amps = pd.DataFrame(np.random.randint(0,100,size=(5, 1)), columns=['value'])
extremas = pd.DataFrame(np.random.randint(0,100,size=(5, 1)), columns=['value'])
# this part
minima = extremas.loc[amps.index, 'value'].reset_index(drop=True)
maxima = extremas.loc[amps.index - 1, 'value'].reset_index(drop=True)
df = pd.DataFrame({'local minima':minima ,'local maxima': maxima})
