【问题标题】:Convert numerical data to categorical in Python在 Python 中将数值数据转换为分类数据
【发布时间】:2020-11-03 21:58:50
【问题描述】:

我有一个 pandas 数据框,其中 fert_Rate 列是生育率。我希望有一个新列,其中这些值是分类而不是数字。我想要的不是 1.0、2.5、4.0,而是(低、中、高)。在 R 中,我会这样写:

attach(mydata)
mydata$fertcat[fert_Rate > 3.5] <- "High"
mydata$fertcat[fert_Rate > 2 & fert_Rate <= 3.5] <- "Medium"
mydata$fertcat[fert_Rate <= 2] <- "Low"
detach(mydata)

在 python 中是否有类似的方法可以做到这一点,还是我应该循环创建列?

【问题讨论】:

    标签: python r pandas dataframe categorical-data


    【解决方案1】:

    使用pd.cut 对您的数据进行分箱。

    df = pd.DataFrame({'fert_Rate': [1, 2, 3, 3.5, 4, 5]})
    >>> df.assign(fertility=pd.cut(df['fert_Rate'], 
                                   bins=[0, 2, 3.5, 999], 
                                   labels=['Low', 'Medium', 'High']))
       fert_Rate fertility
    0        1.0       Low
    1        2.0       Low
    2        3.0    Medium
    3        3.5    Medium
    4        4.0      High
    5        5.0      High
    

    【讨论】:

    • 完美!这正是我所需要的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-04
    • 1970-01-01
    • 2020-04-17
    • 1970-01-01
    • 1970-01-01
    • 2020-12-18
    相关资源
    最近更新 更多