【问题标题】:Group rows by several values in pandas dataframe按熊猫数据框中的几个值对行进行分组
【发布时间】:2021-05-28 13:34:23
【问题描述】:

我有一个这样的熊猫数据框 df:

AgeGroup    Number  Percent
0   0-4     229     1.0
1   15-19   127     1.0
2   20-24   242     1.0
3   25-44   2348    9.0
4   45-64   7063    29.0
5   5-14    144     1.0
6   65-74   4750    19.0
7   75-84   5670    23.0
8   85plus  4198    17.0
9   AllAges 24771   100.0

我希望我能够将这些值分组到更广泛的年龄组中,例如,我曾尝试像这样将年龄 '0-4' 和 '5-14' 分组在一起。

df.loc[(df.AgeGroup == '0-4') & (df.AgeGroup == '5-14'), 'Number'].sum()
#or,
df.query("AgeGroup == '0-4' and AgeGroup == '5-14'")['Number'].sum()

上面给出的值 0 显示零行。

但是,这适用于一个给出 1 行的值。

df.query('AgeGroup == "5-14"')
5   5-14        144     1.0

如何修改它以显示两行?

【问题讨论】:

  • 没有处理查询,因为您使用的是 AND 条件。没有 2 个条目是“0-4”和“5-14”。您是否尝试将其更改为 OR?

标签: python-3.x pandas dataframe sum grouping


【解决方案1】:

没有满足AND条件的AgeGroup:

(df.AgeGroup == '0-4') & (df.AgeGroup == '5-14')

你的意思是或:

(df.AgeGroup == '0-4') | (df.AgeGroup == '5-14')

你也可以使用isin:

df.AgeGroup.isin(['0-4', '5-14'])

【讨论】:

    猜你喜欢
    • 2013-02-28
    • 2019-04-12
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    • 2014-04-23
    • 2020-06-22
    • 2020-04-26
    • 2021-11-02
    相关资源
    最近更新 更多