2014-08-27 25 views
3

我上車計算結果爲數據集中工作機器學習和數據集是這樣編碼列標籤在熊貓的機器學習

buying,maint,doors,persons,lug_boot,safety,class 
vhigh,vhigh,2,2,small,low,unacc 
vhigh,vhigh,2,2,small,med,unacc 
vhigh,vhigh,2,2,small,high,unacc 
vhigh,vhigh,2,2,med,low,unacc 
vhigh,vhigh,2,2,med,med,unacc 
vhigh,vhigh,2,2,med,high,unacc 

我想這些字符串轉換爲唯一枚舉整數縱列。我看到pandas.factorize()是要走的路,但它只能在一列上工作。如何用一個命令一次性分解數據幀。

我試過lambda函數,它不工作。

df.apply(拉姆達C:pd.factorize(c)中,軸= 1)

輸出:

0  ([0, 0, 1, 1, 2, 3, 4], [vhigh, 2, small, low,... 

    1  ([0, 0, 1, 1, 2, 3, 4], [vhigh, 2, small, med,... 

    2  ([0, 0, 1, 1, 2, 3, 4], [vhigh, 2, small, high... 

    3  ([0, 0, 1, 1, 2, 3, 4], [vhigh, 2, med, low, u... 

    4  ([0, 0, 1, 1, 2, 2, 3], [vhigh, 2, med, unacc]) 

    5  ([0, 0, 1, 1, 2, 3, 4], [vhigh, 2, med, high, ... 

我看到編碼值,但不能拔出了這一點從上面的陣列

+0

難道你不想做'df.apply(pd.factorize)'嗎? – EdChum 2014-08-27 15:17:20

回答

6

因式分解返回(值,標籤)的元組。你只需要DataFrame中的值。

In [26]: cols = ['buying', 'maint', 'lug_boot', 'safety', 'class'] 

In [27]: df[cols].apply(lambda x: pd.factorize(x)[0]) 
Out[27]: 
    buying maint lug_boot safety class 
0  0  0   0  0  0 
1  0  0   0  1  0 
2  0  0   0  2  0 
3  0  0   1  0  0 
4  0  0   1  1  0 
5  0  0   1  2  0 

然後將其轉換爲數字數據。

儘管有一個警告:這意味着「低」安全和「高」安全距離「醫療」安全的距離相同。你可能會關閉使用pd.get_dummies更好:

In [37]: dummies = [] 

In [38]: for col in cols: 
    ....:  dummies.append(pd.get_dummies(df[col])) 
    ....:  

In [39]: pd.concat(dummies, axis=1) 
Out[39]: 
    vhigh vhigh med small high low med unacc 
0  1  1 0  1  0 1 0  1 
1  1  1 0  1  0 0 1  1 
2  1  1 0  1  1 0 0  1 
3  1  1 1  0  0 1 0  1 
4  1  1 1  0  0 0 1  1 
5  1  1 1  0  1 0 0  1 

get_dummies有一些可選參數來控制的命名,你可能會想。

+0

非常有用:)非常感謝你。 – pbu 2014-08-28 17:34:49