2016-07-26 102 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。 –