【问题标题】:Pandas groupby .all methodPandas groupby .all 方法
【发布时间】:2022-09-23 02:43:45
【问题描述】:

我试图了解如何使用 .all,例如:

import pandas as pd
df = pd.DataFrame({
    \"user_id\": [1,1,1,1,1,2,2,2,3,3,3,3],
    \"score\":   [1,2,3,4,5,3,4,5,5,6,7,8]
})

当我尝试:

df.groupby(\"user_id\").all(lambda x: x[\"score\"] > 2)

我得到:

         score
user_id       
1         True
2         True
3         True

但我期望:

         score
user_id       
1         False  # Since for first group of users the score is not greater than 2 for all
2         True
3         True

事实上,我通过什么值而不是 2 都无关紧要,结果 DataFrame 总是有 True 作为 score 列。

为什么我得到我得到的结果?我怎样才能得到我的预期结果?

我查看了文档:https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.all.html,但它非常简短,并没有帮助我。

    标签: python pandas


    【解决方案1】:

    groupby.all 不接受任何函数作为参数。唯一的参数 (skipna) 接受布尔值。

    你可能想要:

    df['score'].gt(2).groupby(df['user_id']).all()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-20
      • 1970-01-01
      • 2014-04-26
      • 1970-01-01
      • 2020-06-19
      • 2020-11-28
      • 2021-12-10
      • 2014-09-01
      相关资源
      最近更新 更多