【发布时间】:2019-07-05 19:50:00
【问题描述】:
我面临以下问题:我需要将 Matlab 代码重写为 Pandas。
问题如下: 我有身高差数据。基于滚动窗口,我确定了高度差的移动平均值和标准。当一行的高度差异数据大于移动平均值 + 2*std 时,它将被视为“峰值”(我需要识别)。原因是,一个峰值可以识别一个安装点,这在数据集中没有给出。到目前为止,一切顺利。
现在是我无法解决的更难的部分:可以有多个彼此靠近的峰。当一个峰在另一个峰的 10 个索引内(1 个索引/行 = 0.25 米,因此当一个峰在 2.5 米内)时,需要“合并”这些峰:只有具有最大高度差异的峰需要保留。如果该峰值在 10 个索引内没有被另一个峰值包围,则仅将该值保留为最高安装点。
另一种解决方案可能是将最大的高度差异和索引分配给周围的峰。
我尝试了滚动窗口的 idxmax() 方法,但没有成功。然后我尝试了以下,但仍然无法弄清楚。
首先,我尝试将索引转换为列。 然后我过滤了heightdiff_peak == True的数据框 然后我计算了与下一个索引的差异。 并试图获取当前行差异小于 10 的行的最大值。但这并没有给出正确的解决方案。
数据框如下所示:
df:
Location abs_diff_height heightdiff_peak index difference_next_index
277 9.00 4.000000 True 277 1.0
278 9.25 5.000000 True 278 74.0
352 27.75 6.900000 True 352 39.0
391 37.50 6.000000 True 391 169.0
560 79.75 6.000000 True 560 1.0
561 80.00 5.900000 True 561 1.0
562 80.25 5.900000 True 562 1.0
563 80.50 8.900000 True 563 1.0
564 80.75 9.900000 True 564 1.0
565 81.00 10.900000 True 565 1.0
566 81.25 13.900000 True 566 1.0
我尝试了以下代码,但它不起作用。
def get_max_value(df):
return df.assign(
max_diff_height = lambda df: np.where(df['difference_next_index']<10,
df['abs_diff_height'].rolling(2).max().shift(1),
df['abs_diff_height'])
)
我也尝试过类似的方法:
df[['highest_peak']].rolling(20, center=True).apply(lambda s: s.idxmax(), raw=False)
但是,这只会导致 NaN。
matlab代码为:
%% Snap multiple detections in a row to the highest point of that peak.
% Initialise variables based on first detection value
x=2;
Remember=PeakIndexT(1);
PeakIndex=PeakIndexT(1);
PeakValue=Dataset(PeakIndexT(1));
while x<=length(PeakIndexT)
if PeakIndexT(x)-Remember>10 % If there is more then 10 points (2.5 meters) difference between this and previous detection identify this one as a new one
PeakIndex=[PeakIndex,PeakIndexT(x)];
PeakValue=[PeakValue,Dataset(PeakIndexT(x))];
else % Else merge the detections and use the highest absolute value as the detection peak
if PeakValue(end)<Dataset(PeakIndexT(x))
PeakValue(end)=Dataset(PeakIndexT(x));
PeakIndex(end)=PeakIndexT(x);
end
end
Remember=PeakIndexT(x); % Store previous value for reference in loop
x=x+1;
end
我期望的结果是最大值和索引。
df:
Location abs_diff_height heightdiff_peak index difference_next_index max_value index_max_value
277 9.00 4.000000 True 277 1.0 5.0 278
278 9.25 5.000000 True 278 74.0 5.0 278
352 27.75 6.900000 True 352 39.0 6.9 352
391 37.50 6.000000 True 391 169.0 6.0 591
560 79.75 6.000000 True 560 1.0 13.9 566
561 80.00 5.900000 True 561 1.0 13.9 566
562 80.25 5.900000 True 562 1.0 13.9 566
563 80.50 8.900000 True 563 1.0 13.9 566
564 80.75 9.900000 True 564 1.0 13.9 566
565 81.00 10.900000 True 565 1.0 13.9 566
566 81.25 13.900000 True 566 1.0 13.9 566
【问题讨论】:
标签: python pandas numpy dataframe