简体   繁体   English

如何为Sci-kit Learn重新格式化分类熊猫变量

[英]How to reformat categorical Pandas variables for Sci-kit Learn

Given a pandas dataFrame that looks like this: 给定一个熊猫dataFrame如下所示:

|       | c_0337 | c_0348 | c_0351 | c_0364 |
|-------|:------:|-------:|--------|--------|
| id    |        |        |        |        |
| 11193 |    a   |      f | o      | a      |
| 11382 |    a   |      k | s      | a      |
| 16531 |    b   |      p | f      | b      |
| 1896  |    a   |      f | o      | NaN    |

I am trying to convert the categorical variables to numeric (preferably binary true false columns) I tried using the OneHotEncoder from scikit learn as follows: 我正在尝试将分类变量转换为数字(最好是二进制的true false列),我尝试使用来自scikit的OneHotEncoder学习如下:

from sklearn.preprocessing import OneHotEncoder
enc = OneHotEncoder()
enc.fit([c4k.ix[:,'c_0327':'c_0351'].values])  
OneHotEncoder(categorical_features='all',
   n_values='auto', sparse=True) 

That just gave me: invalid literal for long() with base 10: 'f' 那给了我:以10为底的long()无效文字:'f'

I need to get the data into an array acceptable to Scikit learn, with columns being created with false for most entries (eg very sparse) true for the created column that contains the corresponding letter? 我需要将数据放入Scikit学习可接受的数组中,对于大多数条目(例如,非常稀疏)创建的列都为false,对于包含相应字母的已创建列是否为true?

with NaN being 0=false NaN为0 = false

I suspect I'm way off here? 我怀疑我要离开这里吗? Like not even using the right preprocessor? 像不使用正确的预处理器一样?

Brand new at this so any pointers appreciated the actual dataset has over 1000 such columns...... So then I tried using DictVectorizer as follows: 这是全新的,因此任何指针都赞赏实际数据集有1000多个这样的列……因此,我尝试如下使用DictVectorizer:

from sklearn.feature_extraction import DictVectorizer
vec = DictVectorizer() 
#fill df with zeros Since we don't want NaN
c4kNZ=c4k.ix[:,'c_0327':'c_0351'].fillna(0) 
#Make the dataFrame a Dict 
c4kb=c4kNZ.to_dict() 
sdata = vec.fit_transform(c4kb) 

It gives me float() argument must be a string or a number – I rechecked the dict and it looks ok to me but I guess I have not gotten it formatted correctly? 它给我的float()参数必须是字符串或数字–我重新检查了字典,对我来说似乎还可以,但是我想我没有正确设置其格式?

Is this what you are looking for? 这是你想要的?
It is using get_dummies to convert categorical columns into sparse dummy columns indicating the presence of a value: 它使用get_dummies将分类列转换为指示值存在的稀疏伪列:

In [12]: df = pd.DataFrame({'c_0337':list('aaba'), 'c_0348':list('fkpf')})

In [13]: df
Out[13]:
  c_0337 c_0348
0      a      f
1      a      k
2      b      p
3      a      f

In [14]: pd.get_dummies(df)
Out[14]:
   c_0337_a  c_0337_b  c_0348_f  c_0348_k  c_0348_p
0         1         0         1         0         0
1         1         0         0         1         0
2         0         1         0         0         1
3         1         0         1         0         0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM