按 Pandas 中的特定年龄组分组

Group by Certain Age Group in Pandas

我有一列年龄值需要按列分组。

例如在这个数据框中我有:

并想去:

我这样做是为了尝试过滤掉它并获取数据,但它什么也没返回。

data_df = df[df['Age'] <= 30]
data_df

它无法正常工作,我遇到了一个错误。

ValueError: cannot reindex from a duplicate axis

首先通过删除 + 将列的值转换为数字,然后通过 cut and last create indicators by get_dummies 合并并附加到原始 DataFrame:

df['Age'] = df['Age'].astype(str).str.strip('+').astype(int)

df  = df.join(pd.get_dummies(pd.cut(df['Age'],
                           bins=(0,18,25,29,50,np.inf), 
                           labels=['Under 18','19_to_25','26_to_29','30_to_50','Over 50'])))
print (df)
    Age  Under 18  19_to_25  26_to_29  30_to_50  Over 50
0    12         1         0         0         0        0
1    13         1         0         0         0        0
2    14         1         0         0         0        0
3    18         1         0         0         0        0
4    20         0         1         0         0        0
5    25         0         1         0         0        0
6    30         0         0         0         1        0
7    40         0         0         0         1        0
8    50         0         0         0         1        0
9    60         0         0         0         0        1
10   70         0         0         0         0        1