Python 熊猫:类别数据类型和过滤器
使用pandas 0.18.1,我在过滤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
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