2014-11-05 48 views

回答

6
In [46]: s = Series(list('aaabbbccddefgh')).astype('category') 

In [47]: s 
Out[47]: 
0  a 
1  a 
2  a 
3  b 
4  b 
5  b 
6  c 
7  c 
8  d 
9  d 
10 e 
11 f 
12 g 
13 h 
dtype: category 
Categories (8, object): [a < b < c < d < e < f < g < h] 

In [48]: df = pd.get_dummies(s) 

In [49]: df 
Out[49]: 
    a b c d e f g h 
0 1 0 0 0 0 0 0 0 
1 1 0 0 0 0 0 0 0 
2 1 0 0 0 0 0 0 0 
3 0 1 0 0 0 0 0 0 
4 0 1 0 0 0 0 0 0 
5 0 1 0 0 0 0 0 0 
6 0 0 1 0 0 0 0 0 
7 0 0 1 0 0 0 0 0 
8 0 0 0 1 0 0 0 0 
9 0 0 0 1 0 0 0 0 
10 0 0 0 0 1 0 0 0 
11 0 0 0 0 0 1 0 0 
12 0 0 0 0 0 0 1 0 
13 0 0 0 0 0 0 0 1 

In [50]: x = df.stack() 

# I don't think you actually need to specify ALL of the categories here, as by definition 
# they are in the dummy matrix to start (and hence the column index) 
In [51]: Series(pd.Categorical(x[x!=0].index.get_level_values(1))) 
Out[51]: 
0  a 
1  a 
2  a 
3  b 
4  b 
5  b 
6  c 
7  c 
8  d 
9  d 
10 e 
11 f 
12 g 
13 h 
Name: level_1, dtype: category 
Categories (8, object): [a < b < c < d < e < f < g < h] 

所以我認爲我們需要一個'做'這個函數,因爲它似乎是一個自然操作。也許get_categories(),看到here

6

這是一個幾年,所以這很可能不是一直在pandas工具包回來時,這個問題原本問,但這種做法似乎更容易一些給我。 idxmax將返回對應於最大元素的索引(即具有1的索引)。我們做axis=1,因爲我們想要1出現的列名稱。

編輯:我沒有打擾使它只是一個字符串的類別,但你可以像@Jeff那樣用pd.Categorical(和pd.Series,如果需要)包裝它。

In [1]: import pandas as pd 

In [2]: s = pd.Series(['a', 'b', 'a', 'c']) 

In [3]: s 
Out[3]: 
0 a 
1 b 
2 a 
3 c 
dtype: object 

In [4]: dummies = pd.get_dummies(s) 

In [5]: dummies 
Out[5]: 
    a b c 
0 1 0 0 
1 0 1 0 
2 1 0 0 
3 0 0 1 

In [6]: s2 = dummies.idxmax(axis=1) 

In [7]: s2 
Out[7]: 
0 a 
1 b 
2 a 
3 c 
dtype: object 

In [8]: (s2 == s).all() 
Out[8]: True