我试图做一些类似的事情,但是我遇到了错误。 我有一个包含特征和标签的pandas数据框,需要进行一些转换才能将特征和标签变量发送到机器学习对象:
import pandas
import milk
from scikits.statsmodels.tools import categorical
那么我有:
trainedData=bigdata[bigdata['meta']<15]
untrained=bigdata[bigdata['meta']>=15]
#print trainedData
#extract two columns from trainedData
#convert to numpy array
features=trainedData.ix[:,['ratio','area']].as_matrix(['ratio','area'])
un_features=untrained.ix[:,['ratio','area']].as_matrix(['ratio','area'])
print 'features'
print features[:5]
##label is a string:single, touching,nuclei,dust
print 'labels'
labels=trainedData.ix[:,['type']].as_matrix(['type'])
print labels[:5]
#convert single to 0, touching to 1, nuclei to 2, dusts to 3
#
tmp=categorical(labels,drop=True)
targets=categorical(labels,drop=True).argmax(1)
print targets
输出控制台首先产生:
features
[[ 0.38846334 0.97681855]
[ 3.8318634 0.5724734 ]
[ 0.67710876 1.01816444]
[ 1.12024943 0.91508699]
[ 7.51749674 1.00156707]]
labels
[[single]
[touching]
[single]
[single]
[nuclei]]
我遇到以下错误:
Traceback (most recent call last):
File "/home/claire/Applications/ProjetPython/projet particule et objet/karyotyper/DAPI-Trainer02-MILK.py", line 83, in <module>
tmp=categorical(labels,drop=True)
File "/usr/local/lib/python2.6/dist-packages/scikits.statsmodels-0.3.0rc1-py2.6.egg/scikits/statsmodels/tools/tools.py", line 206, in categorical
tmp_dummy = (tmp_arr[:,None]==data).astype(float)
AttributeError: 'bool' object has no attribute 'astype'
是否可以将dataframe中的category变量“type”转换为int类型'可以接受值'single'、'touching'、'nucleus'、'dusts',我需要用0、1、2、3这样的int值进行转换。
我在回答熊猫0.10.1的问题。
Factor.from_array
似乎起到了作用。前面的答案已经过时了,所以这里有一个将字符串映射到数字的解决方案,它适用于0.18.1版的Pandas。
对于一个系列:
对于数据帧:
如果您有一个字符串或其他对象的向量,并且希望给它分类标签,那么可以使用
Factor
类(在pandas
命名空间中可用):因子具有属性
labels
和levels
:这是针对一维向量的,所以不确定它是否可以立即应用到您的问题上,但请看一看。
顺便说一句,我建议你在statsmodels和/或scikit learn邮件列表上提出这些问题,因为我们大多数人都不经常使用。
相关问题 更多 >
编程相关推荐