使用pandas或statsmodels在python中按条件创建分类变量 [英] create categorical variables by condition in python with pandas or statsmodels

查看:32
本文介绍了使用pandas或statsmodels在python中按条件创建分类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用这种方法从我的数据中创建分类变量:

I want to create categorical variables from my data with this method:

cat.var  condition
1          x > 10
2          x == 10
3          x < 10

我尝试使用 patsy 中的 C() 方法,但它不起作用,我知道在 stata 中我必须使用下面的代码,但是搜索后我没有在 pyhton 中找到任何干净的方法来做到这一点:

I try using C() method from patsy , but it doesn't work, I know in stata I have to use code below, but after searching I didn't find any clean way to do this in pyhton:

generate mpg3    = .   

 (74 missing values generated) 

replace  mpg3    = 1 if (mpg <= 18) 

 (27 real changes made) 

replace  mpg3    = 2 if (mpg >= 19) & (mpg <=23) 

 (24 real changes made) 

replace  mpg3    = 3 if (mpg >= 24) & (mpg <.) 

 (23 real changes made

推荐答案

你可以这样做(我们只为列:a 这样做):

you can do it this way (we will do it just for column: a):

In [36]: df
Out[36]:
     a   b   c
0   10  12   6
1   12   8   8
2   10   5   8
3   14   7   7
4    7  12  11
5   14  11   8
6    7   7  14
7   11   9  11
8    5  14   9
9    9  12   9
10   7   8   8
11  13   9   8
12  13  14   6
13   9   7  13
14  12   7   5
15   6   9   8
16   6  12  12
17   7  12  13
18   7   7   6
19   8  13   9

df.a[df.a < 10] = 3
df.a[df.a == 10] = 2
df.a[df.a > 10] = 1

In [40]: df
Out[40]:
    a   b   c
0   2  12   6
1   1   8   8
2   2   5   8
3   1   7   7
4   3  12  11
5   1  11   8
6   3   7  14
7   1   9  11
8   3  14   9
9   3  12   9
10  3   8   8
11  1   9   8
12  1  14   6
13  3   7  13
14  1   7   5
15  3   9   8
16  3  12  12
17  3  12  13
18  3   7   6
19  3  13   9

In [41]: df.a = df.a.astype('category')

In [42]: df.dtypes
Out[42]:
a    category
b       int32
c       int32
dtype: object

这篇关于使用pandas或statsmodels在python中按条件创建分类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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