【问题标题】:Why do I see the result as True and False .agg() pandas python function?为什么我看到结果为 True 和 False .agg() pandas python 函数?
【发布时间】:2021-07-01 10:20:25
【问题描述】:

快速提问。当我运行这段代码时,我认为真或假是一个故障。为什么会这样?

datamart.groupby(datamart['RFM_Score'] == 9)['MonetaryValue'].agg(np.mean)

enter image description here

【问题讨论】:

    标签: python pandas pandas-groupby


    【解决方案1】:

    您编写的内容将比较结果返回为 True 或 False。看起来像是比较每个值是否高于平均值。

    看起来您只需要 RFM_Score == 9 的行的平均值。如果是这样,请将您的 df 过滤到仅这些行,然后获取这些行的平均值。看这个玩具例子:

    row1list = [8, 1]
    row2list = [9, 2]
    row3list = [9, 4]
    datamart = pd.DataFrame([row1list, row2list, row3list], columns=['RFM_Score', 'MonetaryValue'])
    
    datamart1 = datamart.groupby(datamart['RFM_Score'] == 9)['MonetaryValue'].agg(np.mean)
    print(datamart1)
    # RFM_Score
    # False    1
    # True     3
    
    datamart9s = datamart[datamart['RFM_Score'] == 9]
    mean_of_money_for_9s = datamart9s['MonetaryValue'].agg(np.mean)
    print(mean_of_money_for_9s)
    # Name: MonetaryValue, dtype: int64
    # 3.0
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-10
      • 2022-07-05
      • 2019-10-24
      • 2021-07-02
      • 2023-01-13
      • 2016-02-02
      • 2021-11-18
      • 2015-09-30
      相关资源
      最近更新 更多