2014-09-29 27 views
0

我有这样的数据帧:转换一个熊猫的数据帧的多列哑变量 - Python的

enter image description here

据我所知,使用scikit在Python学习包机器学习任务时,分类变量应该转换为虚拟变量。因此,举例来说,使用scikit的图书馆学我尝试第三列的值转换为虚值,但我的代码没有工作:

from sklearn.preprocessing import LabelEncoder 

x[:, 2] = LabelEncoder().fit_transform(x[:,2]) 

那么,什么是错我的代码?以及如何将所有分类变量转换为数据框中的虚拟变量?

编辑:全回溯是这样的:

--------------------------------------------------------------------------- 
TypeError         Traceback (most recent call last) 
<ipython-input-73-c0d726db979e> in <module>() 
     1 from sklearn.preprocessing import LabelEncoder 
     2 
----> 3 x[:, 2] = LabelEncoder().fit_transform(x[:,2]) 

C:\Users\toshiba\Anaconda\lib\site-packages\pandas\core\frame.pyc in __getitem__(self, key) 
    2001    # get column 
    2002    if self.columns.is_unique: 
-> 2003     return self._get_item_cache(key) 
    2004 
    2005    # duplicate columns 

C:\Users\toshiba\Anaconda\lib\site-packages\pandas\core\generic.pyc in _get_item_cache(self, item) 
    665    return cache[item] 
    666   except Exception: 
--> 667    values = self._data.get(item) 
    668    res = self._box_item_values(item, values) 
    669    cache[item] = res 

C:\Users\toshiba\Anaconda\lib\site-packages\pandas\core\internals.pyc in get(self, item) 
    1653  def get(self, item): 
    1654   if self.items.is_unique: 
-> 1655    _, block = self._find_block(item) 
    1656    return block.get(item) 
    1657   else: 

C:\Users\toshiba\Anaconda\lib\site-packages\pandas\core\internals.pyc in _find_block(self, item) 
    1933 
    1934  def _find_block(self, item): 
-> 1935   self._check_have(item) 
    1936   for i, block in enumerate(self.blocks): 
    1937    if item in block: 

C:\Users\toshiba\Anaconda\lib\site-packages\pandas\core\internals.pyc in _check_have(self, item) 
    1939 
    1940  def _check_have(self, item): 
-> 1941   if item not in self.items: 
    1942    raise KeyError('no item named %s' % com.pprint_thing(item)) 
    1943 

C:\Users\toshiba\Anaconda\lib\site-packages\pandas\core\index.pyc in __contains__(self, key) 
    317 
    318  def __contains__(self, key): 
--> 319   hash(key) 
    320   # work around some kind of odd cython bug 
    321   try: 

TypeError: unhashable type 
+0

你应该提供完整的回溯,而不是只说:“这没”工作“。我怀疑问题在于制作虚拟变量会生成多个列(原始列中的每个不同值都有一个列),因此您无法将其分配回原始列。您可能会想要创建一个包含虚拟列的新DataFrame。 – BrenBarn 2014-09-29 03:32:09

+0

在熊猫的问题中,如果您包含DataFrame的可复制版本,通常会更好。我通常更喜欢'df.to_dict'的输出 – Korem 2014-09-29 06:41:47

回答

3

我不认为LabelEncoder功能将您的数据,以虚拟变量(见scikit-learn.org/LabelEncoder),但变量创建新的数值标签。

我使用熊猫的get_dummies函数来做到这一点(请参阅pandas.pydata.org/dummies)。在一个简单的例子下。

创建简单DataFrame具有分类和数值数据

import pandas as pd 
X = pd.DataFrame({"Var1": ["a", "a", "b"], 
        "Var2": ["a", "b", "c"], 
        "Var3": [1, 2, 3]}, 
        dtype = "category") 
X["Var3"] = X["Var3"].astype(int) 

变换数据,以虚拟变量

pd.get_dummies(X) 

缺货[4]:

Var3 Var1_a Var1_b Var2_a Var2_b Var2_c 
0  1  1  0  1  0  0 
1  2  1  0  0  1  0 
2  3  0  1  0  0  1 

注意Var1,转化两个虚拟变量,但你可能想要h所有三个类别均为[a, b, c]。您需要添加新的类别。

X["Var1"].cat.add_categories("c", inplace=True) 

而结果:

pd.get_dummies(X) 

出[6]:

Var3 Var1_a Var1_b Var1_c Var2_a Var2_b Var2_c 
0  1  1  0  0  1  0  0 
1  2  1  0  0  0  1  0 
2  3  0  1  0  0  0  1 

希望这有助于