将数值数据更改为分类数据- pandas [英] Change numerical Data to Categorical Data - Pandas

查看:152
本文介绍了将数值数据更改为分类数据- pandas 的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个熊猫数据框,其中有一个数字列金额".数量从0到20000不等.我想将其更改为定义范围的分类变量.因此,分类变量为:

I have a pandas dataframe which has a numerical column "amount". The amount varies from 0 to 20000. I want to change it into categorical variable which defines a range. So, the categorical variable would be :

  1. 0-1000 $之间
  2. 1000-2000 $之间,依此类推..直到19000-20000 $

我无法弄清楚如何更改列.我可以将其更改为这样的二进制值:

I am unable to figure out how to change the column. I can change it to a binary values like this :

months["value"] = np.where(months['amount']>=450, 'yes', 'no') 

但是,对于具有两个以上值的分类变量,该怎么办呢?

But, how to do it for categorical variable having more than 2 values?

推荐答案

您可以使用 cut :

You can use cut:

df = pd.DataFrame({'B':[4000,5000,4000,9000,5,11040]})

df['D'] = pd.cut(df['B'], range(0, 21000, 1000))
print (df)
       B               D
0   4000    (3000, 4000]
1   5000    (4000, 5000]
2   4000    (3000, 4000]
3   9000    (8000, 9000]
4      5       (0, 1000]
5  11040  (11000, 12000]

这篇关于将数值数据更改为分类数据- pandas 的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆