-1

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
Thanos
  • 2,472
  • 1
  • 16
  • 33
Mehdi
  • 1,260
  • 2
  • 16
  • 36

2 Answers2

2

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
MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419
1

I'm using this df as a sample.

>>> df
     A
0    3
1   13
2   10
3   31

You could use .ix like this:

df['CAT'] = [np.nan for i in range(len(df.index))]
df.ix[df.A > 10, 'CAT'] = 1
df.ix[df.A == 10, 'CAT'] = 2
df.ix[df.A < 10, 'CAT'] = 3

Or define a function to do the job, like this:

def do_the_job(x):
    ret = 3
    if (x > 10):
        ret = 1
    elif (x == 10):
        ret = 2

    return ret

and finally run this over the right Series in your df, like this:

>> df['CAT'] = df.A.apply(do_the_job)
>> df
     A   CAT
0    3     3
1   13     1
2   10     2
3   31     1

I hope this help!

Thanos
  • 2,472
  • 1
  • 16
  • 33