Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
220 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...