当前位置: 代码迷 >> python >> 熊猫:类别dtype和过滤器
  详细解决方案

熊猫:类别dtype和过滤器

热度:65   发布时间:2023-06-14 08:48:03.0

使用熊猫0.18.1,我其过滤列时实现不同的行为dtypecategory 这是一个最小的例子。

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时,该函数需要一个额外的过滤器。

这是预期的行为吗?

如果检查 ,这是预期的行为:

诸如Series.value_counts()之类的Series方法将使用所有类别,即使数据中不存在某些类别:

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