【问题标题】:Pandas: category dtype and filterPandas:类别 dtype 和过滤器
【发布时间】:2017-02-16 16:27:26
【问题描述】:

使用pandas 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 时需要额外的过滤器。

这是预期的行为吗?

【问题讨论】:

    标签: python pandas filter categorical-data


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-07
      • 1970-01-01
      • 2019-03-25
      • 2015-02-25
      • 2019-08-11
      • 1970-01-01
      相关资源
      最近更新 更多