【发布时间】:2017-02-16 16:27:26
【问题描述】:
使用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.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