如何在Pandas中按条件用众数替换Product A的Price值
Pandas实现Product A的Price替换为其列的众数
原始数据集
| Product | Price |
|---|---|
| A | 5 |
| A | 6 |
| A | 7 |
| B | 8 |
| B | 8 |
| B | 4 |
| A | 5 |
| A | 5 |
| A | 5 |
| A | Nan |
| c | 4 |
| D | 3 |
实现步骤与代码
导入依赖并加载数据
先导入pandas,同时构造目标数据集:import pandas as pd # 构造数据集 data = { 'Product': ['A', 'A', 'A', 'B', 'B', 'B', 'A', 'A', 'A', 'A', 'c', 'D'], 'Price': [5, 6, 7, 8, 8, 4, 5, 5, 5, pd.NA, 4, 3] } df = pd.DataFrame(data)计算Product A的Price列众数
筛选出Product为A的行,排除空值后取众数(此处众数唯一为5):# 计算Product A的Price众数,dropna=True排除空值 a_price_mode = df[df['Product'] == 'A']['Price'].mode(dropna=True)[0]替换Product A对应的Price值
用loc定位符合条件的行,统一替换Price为计算出的众数:# 替换所有Product为A的行的Price为众数 df.loc[df['Product'] == 'A', 'Price'] = a_price_mode
最终结果
执行代码后,所有Product为A的行Price均会变为5,数据集更新为:
| Product | Price |
|---|---|
| A | 5 |
| A | 5 |
| A | 5 |
| B | 8 |
| B | 8 |
| B | 4 |
| A | 5 |
| A | 5 |
| A | 5 |
| A | 5 |
| c | 4 |
| D | 3 |
内容的提问来源于stack exchange,提问作者Mathew John
相关产品推荐
相关产品推荐

