【问题标题】:Drop pandas rows for entire group based on condition根据条件删除整个组的 pandas 行
【发布时间】:2019-10-06 23:36:11
【问题描述】:
import seaborn
df = seaborn.load_dataset('flights')

我想放弃每年平均乘客人数少于 200 人的年份。我试过这个

df[df.groupby(['year'])['passengers'].mean() > 200] 

但得到这个错误:

*** pandas.core.indexing.IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match).

在正确答案中,数据框应删除这些年份的行: 1949、1950、1951、1952

【问题讨论】:

  • 我猜你想要:df[df.groupby('year')['passengers'].transform('mean') > 200]

标签: python pandas


【解决方案1】:

我认为,你需要:

  • 分组
  • 过滤组,检查 passengers 在 当前组 > 300。

所以代码应该是:

df.groupby(['year']).filter(lambda x: x.passengers.mean() > 300)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-02
    • 1970-01-01
    • 2018-06-12
    • 2018-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多