【问题标题】:How to encode a range of values using pandas如何使用 pandas 对一系列值进行编码
【发布时间】:2017-10-24 08:47:50
【问题描述】:

我有一个 pandas 数据框和一个列 age。我想将其编码为按特定范围分隔的分类值,例如,15 岁以下的年龄应为 0,15 至 30 岁应更改为 1,依此类推。

我发现了这种方法(在经历了关于使用 & 和 and 的巨大困惑之后)

age = X.loc[:, 'Age']

age[ age<15 ] = 0
age[ (15<age) & (age<=30) ] = 1
age[ (30<age) & (age<=50) ] = 2
age[ (50<age) & (age<=80) ] = 3

这是最好的方法吗?我可以这样做吗,例如使用 LabelEncoder?

【问题讨论】:

    标签: python pandas indexing


    【解决方案1】:

    你可以使用cut:

    df = pd.DataFrame({'Age':[0,1,14,15,30,31,50,51,79,80]})
    
    bins = [0,14,30,50,80]
    labels=[0,1,2,3]
    df['bins'] = pd.cut(df['Age'], bins=bins, labels=labels, include_lowest=True)
    print (df)
       Age bins
    0    0    0
    1    1    0
    2   14    0
    3   15    1
    4   30    1
    5   31    2
    6   50    2
    7   51    3
    8   79    3
    9   80    3
    

    【讨论】:

    • 谢谢它正在工作,但有这个警告。我尝试将 df['Bins'] 更改为 df.iloc[:, 'Bins'] 但同样,我似乎收到了同样的警告。我应该担心这个吗? SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead
    • 我认为之前的代码有问题,希望帮助this
    猜你喜欢
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多