简体   繁体   English

在 Python 中将数值数据转换为分类数据

[英]Convert numerical data to categorical in Python

I have a pandas dataframe with the column fert_Rate for fertility rate.我有一个 Pandas 数据框,列 fert_Rate 表示生育率。 I want to have a new column with these values as categorical instead of numerical.我想有一个新列,这些值是分类而不是数字。 Instead of 1.0, 2.5, 4.0 I want something like (low, medium, high).我想要的不是 1.0、2.5、4.0,而是(低、中、高)。 In RI would have written something like this:在 RI 中会这样写:

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)

Is there a similar way to do it in python or should I just loop over the column to create?有没有类似的方法可以在 python 中做到这一点,还是我应该循环遍历列来创建?

Use pd.cut to bin your data.使用pd.cutpd.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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 Python 中将分类数据转换为数值数据 - Convert categorical data into numerical data in Python 如何在 python pandas 的 for 循环中将分类数据转换为数值数据 - how to convert categorical data to numerical data in for loop in python pandas python - 如何在带有分类和数值列的python中将每日数据转换为每周或每月? - How to convert daily data into weekly or monthly in python with categorical and numerical column? 我想在 Python 中将分类变量转换为数值 - I want to convert the categorical variable to numerical in Python 如何将一系列数值数据转换为特定的分类数据? - How can convert a range of numerical data to a particular categorical data? 将分类数据编码为数值 - Encoding categorical data to numerical 如何在张量流中将数值分类数据转换为稀疏张量? - How to convert numerical categorical data into Sparse tensors in tensorflow? 如何在不增加数据大小的情况下将大熊猫中的分类变量转换为数值? - How to convert categorical variable to numerical in pandas without increasing size of data? PySpark MLLib:将数值转换为分类 - PySpark MLLib: Convert numerical to categorical 如何将数字重新编码为分类数据 - How to recode numerical to categorical data
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM