我得到了这一系列带有索引的数据点;所以数据框看起来像这样:
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
的结果,我编写了另一个函数来查找极值对的振幅(也称为局部最小值和局部最大值之间的值差)... I' 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})
关于python - 如何合并两个具有不同索引的数据帧?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48941345/