简体   繁体   English

使用pandas将分类值转换为二进制

[英]Converting categorical values to binary using pandas

I am trying to convert categorical values into binary values using pandas. 我正在尝试使用pandas将分类值转换为二进制值。 The idea is to consider every unique categorical value as a feature (ie a column) and put 1 or 0 depending on whether a particular object (ie row) was assigned to this category. 我们的想法是将每个唯一的分类值视为一个特征(即一列),并根据特定对象(即行)是否分配给该类别而放置1或0。 The following is the code: 以下是代码:

data = pd.read_csv('somedata.csv')
converted_val = data.T.to_dict().values()
vectorizer = DV( sparse = False )
vec_x = vectorizer.fit_transform( converted_val )
numpy.savetxt('out.csv',vec_x,fmt='%10.0f',delimiter=',')

My question is, how to save this converted data with the column names ?. 我的问题是,如何使用列名保存这些转换后的数据 In the above code, I am able to save the data using numpy.savetxt function, but this simply saves the array and the column names are lost. 在上面的代码中,我可以使用numpy.savetxt函数保存数据,但这只是保存数组并且列名丢失。 Alternatively, is there a much efficient way to perform the above operation?. 或者,是否有一种非常有效的方法来执行上述操作?

You mean "one-hot" encoding? 你的意思是“一热”编码?

Say you have the following dataset: 假设您有以下数据集:

import pandas as pd
df = pd.DataFrame([
            ['green', 1, 10.1, 0], 
            ['red', 2, 13.5, 1], 
            ['blue', 3, 15.3, 0]])

df.columns = ['color', 'size', 'prize', 'class label']
df

在此输入图像描述

Now, you have multiple options ... 现在,您有多种选择......

A) The Tedious Approach A)繁琐的方法

color_mapping = {
           'green': (0,0,1),
           'red': (0,1,0),
           'blue': (1,0,0)}

df['color'] = df['color'].map(color_mapping)
df

在此输入图像描述

import numpy as np
y = df['class label'].values
X = df.iloc[:, :-1].values
X = np.apply_along_axis(func1d= lambda x: np.array(list(x[0]) + list(x[1:])), axis=1, arr=X)

print('Class labels:', y)
print('\nFeatures:\n', X)

Yielding: 产量:

Class labels: [0 1 0]

Features:
 [[  0.    0.    1.    1.   10.1]
 [  0.    1.    0.    2.   13.5]
 [  1.    0.    0.    3.   15.3]]

B) Scikit-learn's DictVectorizer B)Scikit-learn的DictVectorizer

from sklearn.feature_extraction import DictVectorizer
dvec = DictVectorizer(sparse=False)

X = dvec.fit_transform(df.transpose().to_dict().values())
X

Yielding: 产量:

array([[  0. ,   0. ,   1. ,   0. ,  10.1,   1. ],
       [  1. ,   0. ,   0. ,   1. ,  13.5,   2. ],
       [  0. ,   1. ,   0. ,   0. ,  15.3,   3. ]])

C) Pandas' get_dummies C)熊猫的get_dummies

pd.get_dummies(df)

在此输入图像描述

It seems that you are using scikit-learn's DictVectorizer to convert the categorical values to binary. 您似乎正在使用scikit-learn的DictVectorizer将分类值转换为二进制。 In that case, to store the result along with the new column names, you can construct a new DataFrame with values from vec_x and columns from DV.get_feature_names() . 在这种情况下,存储与新的列名一起的结果,你可以构建从值的新数据框中vec_x从和列DV.get_feature_names() Then, store the DataFrame to disk (eg with to_csv() ) instead of the numpy array. 然后,将DataFrame存储到磁盘(例如,使用to_csv() )而不是numpy数组。

Alternatively, it is also possible to use pandas to do the encoding directly with the get_dummies function: 或者,也可以使用pandas直接使用get_dummies函数进行编码:

import pandas as pd
data = pd.DataFrame({'T': ['A', 'B', 'C', 'D', 'E']})
res = pd.get_dummies(data)
res.to_csv('output.csv')
print res

Output: 输出:

   T_A  T_B  T_C  T_D  T_E
0    1    0    0    0    0
1    0    1    0    0    0
2    0    0    1    0    0
3    0    0    0    1    0
4    0    0    0    0    1

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

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