2016-07-26 103 views
1

我想重命名類別並將缺少的類別添加到系列。重命名類別並將缺失的類別添加到系列PANDAS

我的代碼:

codedCol = bdAu['Bordersite'] 
print 'pre:' 
print codedCol.head(10) 
codedCol = codedCol.astype('category') 
codedCol = codedCol.cat.set_categories(['a','b','c','d','e','f','g','h','i','j']) 
print 'post:' 
print codedCol.head(10) 

當我這樣做,我得到結果爲NaN。

pre: 
0 3 
1 3 
2 2 
3 2 
4 3 
5 4 
6 5 
7 3 
8 3 
9 3 
Name: Bordersite, dtype: int64 
post: 
0 NaN 
1 NaN 
2 NaN 
3 NaN 
4 NaN 
5 NaN 
6 NaN 
7 NaN 
8 NaN 
9 NaN 
dtype: category 
Categories (10, object): [a, b, c, d, ..., g, h, i, j] 

我在這裏做錯了什麼?

感謝 Kheeran

+0

什麼是你理想的結果? –

+0

我已經添加了一個答案...讓我知道它是否有幫助。 –

回答

1

第一或創建catagories可以使用.astype('category'),但categories從您的列或Categorical添加參數categories定義在哪裏。

您可以使用:

codedCol = bdAu['Bordersite'] 
codedCol = pd.Series(pd.Categorical(codedCol, categories=[0,1,2,3,4,5,6,7,8,9])) 
print (codedCol) 
0 3 
1 3 
2 2 
3 2 
4 3 
5 4 
6 5 
7 3 
8 3 
9 3 
dtype: category 
Categories (10, int64): [0, 1, 2, 3, ..., 6, 7, 8, 9] 

然後rename_categories,但項目的類別數量必須相同,否則錯誤:

ValueError: new categories need to have the same number of items than the old categories!

codedCol = codedCol.cat.rename_categories(['a','b','c','d','e','f','g','h','i','j']) 
print (codedCol) 
0 d 
1 d 
2 c 
3 c 
4 d 
5 e 
6 f 
7 d 
8 d 
9 d 
dtype: category 
Categories (10, object): [a, b, c, d, ..., g, h, i, j] 
+0

謝謝jezrael。這正是我所期待的。 Jossie,謝謝你的解釋。 – user2663139

1

你設置的類別如下:。 codedCat列中的當前值與任何類別都不匹配。因此,他們重新設置爲NaN。如要進一步瞭解,考慮這個例子from the docs

In [10]: raw_cat = pd.Categorical(["a","b","c","a"], categories=["b","c","d"], 
    ....:       ordered=False) 
    ....: 
In [11]: s = pd.Series(raw_cat) 

In [12]: s 
Out[12]: 
0 NaN 
1  b 
2  c 
3 NaN 
dtype: category 
Categories (3, object): [b, c, d] 

由於"a"是不是一個類別,它被重新設置爲NaN

+0

爲什麼DOWNVOTE? –

+0

@jezrael編輯您的代碼,以便我可以刪除downvote。 –