【问题标题】:Unable to calculate the aggregated mean无法计算聚合平均值
【发布时间】:2022-01-22 18:16:40
【问题描述】:

我有一个这种形式的数据集:

Customer_key  purcahse_amount   Date
12633           4435           08/07/2021
34243           7344           11/11/2021
54355           4642           10/11/2020
12633           6322           11/12/2021

Purchase_amount 的 Nan 值很少....我想用 purcahse_amount 的平均值替换 Nan 值,但应该只为那个特定的 customer_key 计算平均值。例如,如果您看到customer_key=12633 在第 1 行和第 4 行中重复。因此,对于具有customer_key=12633 的任何行,如果缺少purcahse_amount 的值,则将其替换为该purchase_amount 的平均值customer_key=12633 的所有行中。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您可以groupby "Customer_key" 然后计算 "purchase_amount" 的平均值并将其转换为 DataFrame(我们需要对其进行转换以在 np.where 中使用它,其中要选择的值必须是可广播的)。请注意,mean 方法默认会跳过 NaN 值,因此它会转换非 NaN 值的平均值。

    然后使用np.where,具体取决于“purchase_amount”是否为 NaN 或未填写组特定平均值或保持原始值。

    means = df.groupby('Customer_key')['purchase_amount'].transform('mean')
    df['purchase_amount'] = np.where(df['purchase_amount'].isna(), means, df['purchase_amount'])
    

    或者你可以使用fillna:

    df['purchase_amount'] = df['purchase_amount'].fillna(means)
    

    例如,如果您有df,如下所示:

       Customer_key  purchase_amount        Date
    0         12633           4435.0  08/07/2021
    1         34243           7344.0  11/11/2021
    2         54355           4642.0  10/11/2020
    3         12633           6322.0  11/12/2021
    3         12633              NaN  11/12/2021
    

    以上两个选项都会产生:

       Customer_key  purchase_amount        Date
    0         12633           4435.0  08/07/2021
    1         34243           7344.0  11/11/2021
    2         54355           4642.0  10/11/2020
    3         12633           6322.0  11/12/2021
    3         12633           5378.5  11/12/2021
    

    【讨论】:

    • 您的第二步(即使用fillna)显示错误:ValueError: cannot reindex from a duplicate axis
    • 是的,它正在工作
    • 是否有可能以某种方式修改第二个,以便它也可以工作
    • @Rishavv 我更新了。看看它现在是否有效
    • 是的,谢谢
    猜你喜欢
    • 2023-04-05
    • 2012-10-11
    • 2014-08-12
    • 1970-01-01
    • 2016-02-15
    • 2018-11-16
    • 2020-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多