2017-02-16 142 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 

值虽然过滤器有效,但这种行为对我来说似乎不寻常。例如,可以使用该过滤器来排除pivot_table函数中的未来列,该函数在处理category时需要额外的过滤器。

这是预期的行为吗?

回答

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

我明白了。感谢您强调这一点。 –