2016-07-26 4 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

まずたり、.astype('category')を使用することができますcatagoriesを作成しますが、定義されたパラメータ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

ありがとうございます。それが私が探していたものです。 Jossie、説明をいただきありがとうございます。 – user2663139

1

は、次のカテゴリを設定しました。 codedCatの列の現在の値は、いずれのカテゴリとも一致しません。したがって、彼らはNaNに再設定されます。 "a"がカテゴリではないので、それはNaNに再集合を取得

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] 

:さらに読書のために、この例from the docsを考えます。

+0

なぜダウンリスト? –

+0

@jezraelはあなたのコードを編集するので、私はdownvoteを削除することができます。 –

関連する問題