在Pandas DataFrame中用groupby调用find_peaks()遇KeyError求助
解决分组调用find_peaks时的KeyError问题
问题原因
find_peaks返回的peaks是当前分组内的位置索引(从0开始的整数位置),而非原DataFrame的索引标签。用这些位置值去匹配group的索引(原DataFrame的索引),自然找不到对应键,触发KeyError。
解决方案
方案1:用iloc替代loc按位置赋值
直接利用iloc按位置定位的特性,匹配find_peaks返回的位置索引:
def find_peaks_in_group(group): peaks, peak_properties = find_peaks(group['RFPower'], prominence=1, height=0.7) group['peaks'] = False # 通过iloc按位置设置peaks列 group.iloc[peaks, group.columns.get_loc('peaks')] = True group['peak_heights'] = 0.0 # 同理设置peak_heights列 group.iloc[peaks, group.columns.get_loc('peak_heights')] = peak_properties['peak_heights'] return group result_df = df.groupby('ID', group_keys=False).apply(find_peaks_in_group)
方案2:重置分组索引为连续序列
先将分组的索引重置为0开始的连续值,处理完成后再恢复原索引:
def find_peaks_in_group(group): # 重置分组索引,保留原索引到临时列 group = group.reset_index(drop=False) peaks, peak_properties = find_peaks(group['RFPower'], prominence=1, height=0.7) group['peaks'] = False group.loc[peaks, 'peaks'] = True group['peak_heights'] = 0.0 group.loc[peaks, 'peak_heights'] = peak_properties['peak_heights'] # 恢复原索引 group = group.set_index('index') return group result_df = df.groupby('ID', group_keys=False).apply(find_peaks_in_group)
注意事项
两种方案核心都是让peaks的取值能匹配到分组内的行定位:iloc直接识别位置,重置索引则是让loc能匹配到连续的标签值。
内容的提问来源于stack exchange,提问作者thentangler
相关产品推荐
相关产品推荐

