【问题标题】:Group by Certain Age Group in PandasPandas 中按特定年龄组分组
【发布时间】:2022-01-13 11:07:44
【问题描述】:

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

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

并且想去:

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

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

它不能正常工作,我得到了一个错误。

ValueError: 无法从重复的轴重新索引

【问题讨论】:

    标签: python pandas jupyter-notebook


    【解决方案1】:

    首先通过删除+将列的值转换为数字,然后通过cut进行分箱,最后通过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
    

    【讨论】:

    • 谢谢!它就像魔术一样!
    猜你喜欢
    • 1970-01-01
    • 2020-10-27
    • 1970-01-01
    • 1970-01-01
    • 2016-11-24
    • 2012-02-04
    • 2021-10-16
    相关资源
    最近更新 更多