You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pandas中按条件用众数替换Product A的Price值

Pandas实现Product A的Price替换为其列的众数

原始数据集

ProductPrice
A5
A6
A7
B8
B8
B4
A5
A5
A5
ANan
c4
D3

实现步骤与代码

  1. 导入依赖并加载数据
    先导入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)
    
  2. 计算Product A的Price列众数
    筛选出Product为A的行,排除空值后取众数(此处众数唯一为5):

    # 计算Product A的Price众数,dropna=True排除空值
    a_price_mode = df[df['Product'] == 'A']['Price'].mode(dropna=True)[0]
    
  3. 替换Product A对应的Price值
    用loc定位符合条件的行,统一替换Price为计算出的众数:

    # 替换所有Product为A的行的Price为众数
    df.loc[df['Product'] == 'A', 'Price'] = a_price_mode
    

最终结果

执行代码后,所有Product为A的行Price均会变为5,数据集更新为:

ProductPrice
A5
A5
A5
B8
B8
B4
A5
A5
A5
A5
c4
D3

内容的提问来源于stack exchange,提问作者Mathew John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 07:07:02