-1

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

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

我尝试使用来自的C() 方法patsy,但它不起作用,我知道在 stata 中我必须使用下面的代码,但在搜索后我没有找到任何干净的方法来做到这一点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
4

2 回答 2

2

你可以这样做(我们将只为列:)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
于 2016-04-23T22:55:53.673 回答
1

我使用这个 df 作为示例。

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

你可以这样使用.ix

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

或者定义一个函数来完成这项工作,如下所示:

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

    return ret

最后在你的df中正确的系列上运行它,如下所示:

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

我希望这有帮助!

于 2016-04-23T22:59:19.037 回答