如何在Pandas中基于percent_perfect列最小绝对值获取对应median_sale_price值?
解决方案
你已经成功获取了每行中绝对值最小的percent_perfect列名,接下来只需要将这些列名映射到对应的median_sale_price列,再提取对应值即可。以下是两种高效实现方式:
方法一:批量替换列名 + 高效取值(推荐大数据集)
# 获取每行绝对值最小的percent_perfect列名 min_perfect_cols = df.filter(like='percent_perfect_').abs().idxmin(axis=1) # 替换列名前缀,得到对应的median_sale_price列名 median_cols = min_perfect_cols.str.replace('percent_perfect_', 'median_sale_price_') # 提取对应价格值,添加为新列 df['group_price'] = df.lookup(df.index, median_cols)
方法二:逐行匹配(适合小数据集,逻辑更直观)
def get_matching_price(row): # 找到当前行绝对值最小的percent_perfect列 min_col = row.filter(like='percent_perfect_').abs().idxmin() # 转换为对应的价格列名 price_col = min_col.replace('percent_perfect_', 'median_sale_price_') return row[price_col] df['group_price'] = df.apply(get_matching_price, axis=1)
关键逻辑说明
两种方法的核心都是利用列名的对应关系:percent_perfect_xxx_diff和median_sale_price_xxx的后缀(1-5/6-10等)完全匹配,只需替换前缀即可完成映射。其中方法一的df.lookup是向量化操作,比逐行apply效率更高,适合处理大规模数据。
内容的提问来源于stack exchange,提问作者biviz
相关产品推荐
相关产品推荐

