2017-02-16 10 views
1

パンダ0.18.1を使用すると、dtypecategoryのカラムをフィルタリングするときに違った動作が実現しました。ここには最小の例があります。整数型の列の値のいずれかをフィルタリングパンダ:カテゴリdtypeとフィルタ

import pandas as pd 
import numpy as np 

l = np.random.randint(1, 4, 50) 
df = pd.DataFrame(dict(c_type=l, i_type=l)) 
df['c_type'] = df.c_type.astype('category') 

df.info() 

<class 'pandas.core.frame.DataFrame'> 
RangeIndex: 50 entries, 0 to 49 
Data columns (total 2 columns): 
c_type 50 non-null category 
i_type 50 non-null int64 
dtypes: category(1), int64(1) 
memory usage: 554.0 bytes 

df[df.i_type.isin([1, 2])].i_type.value_counts() 

2 20 
1 17 
Name: i_type, dtype: int64 

につながるが、カテゴリタイプ列に同じフィルタリングエントリー

df[df.c_type.isin([1, 2])].c_type.value_counts() 

2 20 
1 17 
3  0 
Name: c_type, dtype: int64 

ようにフィルタリングされた値を保持しますフィルタは動作しますが、動作は私にとっては珍しいようです。例えば、categoryを扱うときに余分なフィルタを必要とするpivot_table関数から将来の列を除外するためにフィルタを使用できます。

これは正常な動作ですか?

答えて

1

はそれは、行動を期待されているかどうかを確認categorical docs

Series.value_counts()は、いくつかのカテゴリがデータ内に存在しない場合でも、すべてのカテゴリを使用するよう

シリーズ方法

In [100]: s = pd.Series(pd.Categorical(["a","b","c","c"], categories=["c","a","b","d"])) 

In [101]: s.value_counts() 
Out[101]: 
c 2 
b 1 
a 1 
d 0 
dtype: int64 

フィルタが5(値が現在ありません)の場合、各カテゴリに0を取得してください:

print (df[df.c_type.isin([5])].c_type.value_counts()) 
3 0 
2 0 
1 0 
Name: c_type, dtype: int64 
+0

です。この点を強調していただきありがとうございます。 –

関連する問題