Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 熊猫:类别数据类型和过滤器_Python_Pandas_Filter_Categorical Data - Fatal编程技术网

Python 熊猫:类别数据类型和过滤器

Python 熊猫:类别数据类型和过滤器,python,pandas,filter,categorical-data,Python,Pandas,Filter,Categorical Data,使用pandas 0.18.1,我在过滤dtype为category的列时实现了一种不同的行为。这里是一个最小的例子 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.c

使用pandas 0.18.1,我在过滤
dtype
category
的列时实现了一种不同的行为。这里是一个最小的例子

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.c_type.isin([1, 2])].c_type.value_counts()

2    20
1    17
3     0
Name: c_type, dtype: int64
虽然过滤器可以工作,但这种行为对我来说似乎不寻常。例如,过滤器可用于从
pivot\u表
函数中排除未来的列,该函数在处理
类别
时需要额外的过滤器


这是预期的行为吗?

这是预期的行为,如果选中:

Series.value_counts()这样的系列方法将使用所有类别,即使数据中不存在某些类别:

因此,如果按
5
进行筛选(值不存在),则为每个类别获取
0

print (df[df.c_type.isin([5])].c_type.value_counts())
3    0
2    0
1    0
Name: c_type, dtype: int64
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
print (df[df.c_type.isin([5])].c_type.value_counts())
3    0
2    0
1    0
Name: c_type, dtype: int64