如何根据 pandas 中的日期将列中的值汇总到与给定条件匹配的组中?

How do I sum up values in a column into groups that match a given condition by date in pandas?

我有一个像这样的年龄组数据框

    Date            AgeGroup            Quantity
1   2020-12-08      18 - 29             1
2   2020-12-08      30 - 49             4
3   2020-12-08      50 - 54             0
4   2020-12-08      55 - 59             1
5   2020-12-08      60 - 64             1
6   2020-12-08      65 - 69             0
7   2020-12-08      70 - 74             3
8   2020-12-08      75 - 79             2
9   2020-12-08      80+                 1
....
10  2020-12-09      18 - 29             0
11  2020-12-09      30 - 49             2
12  2020-12-09      50 - 54             1
13  2020-12-09      55 - 59             2
14  2020-12-09      60 - 64             3
15  2020-12-09      65 - 69             0
16  2020-12-09      70 - 74             1
17  2020-12-09      75 - 79             1
18  2020-12-09      80+                 1

我想按三个更广泛的年龄组总结每个日期的数字,如下所示:

1   2020-12-08      18 - 59             6
2   2020-12-08      60+                 7
3   2020-12-08      75+                 3
...
4   2020-12-09      18 - 59             5
5   2020-12-09      60+                 5
6   2020-12-09      75+                 2

(第一年龄段59岁以下,第二年龄段60岁以上,第三年龄段75岁以上)

我试过以下方法:

df1 = df.loc[(df['AgeGroup'] == '18 - 29') | (df['AgeGroup'] == '30 - 49') | (df['AgeGroup'] == '50 - 54') | (df['AgeGroup'] == '55 - 59') , 'Quantity'].sum()

但是,这没有按日期细分,因为它只给出了所有日期这些年龄组的总和。

这个我也试过了

df.groupby(['Date', 'AgeGroup'])['Quantity'].sum()
Date        AgeGroup         
2020-12-08  18 - 29               1
            30 - 49               4
            50 - 54               0
            55 - 59               2
            60 - 64               1
            65 - 69               0
            70 - 74               3
            75 - 79               2

2020-12-09  18 - 29               0
            30 - 49               2
            50 - 54               1
            55 - 59               2
            60 - 64               3
            65 - 69               0
            70 - 74               1
            75 - 79               1

我仍然不知道如何在日期内组合这些年龄组。谢谢你的任何想法。

您可以通过 Series.str.extract 获取第一个数值,通过 60 进行比较并通过 np.where 设置为 2 组:

m = df['AgeGroup'].str.extract('(\d+)', expand=False).astype(int) < 60
df['AgeGroup'] = np.where(m, '18 - 59', '60+')

df1 = df.groupby(['Date', 'AgeGroup'])['Quantity'].sum()
print (df1)
Date        AgeGroup
2020-12-08  18 - 59     7
            60+         6
2020-12-09  18 - 59     5
            60+         5
Name: Quantity, dtype: int64