带有分类的Pandas DataFrame无法进行比较

时间:2016-01-17 22:26:42

标签: python pandas

比较没有分类列的数据框:

In[1]: df = pd.DataFrame([[4,2,9],[3,8,2],[2,1,6]], columns=['one', 'two', 'three'])

In[2]: df
Out[1]: 
   one  two  three
0    4    2      9
1    3    8      2
2    2    1      6
In[3]: df == 2
Out[2]: 
     one    two  three
0  False   True  False
1  False  False   True
2   True  False  False

如果df有分类,这不也可以吗?

In[4]: df['two'] = df['two'].astype('category')
df == 3
Traceback (most recent call last):
<snip>
ValueError: Wrong number of dimensions

毕竟,只比较系列作品:

In[5]: df['two'] == 2
Out[3]: 
0     True
1    False
2    False
Name: two, dtype: bool

1 个答案:

答案 0 :(得分:1)

你可以使用DataFrame方法apply,它将一个函数应用于框架的所有元素。当变量是分类时,以下行有效:

df.apply(lambda x: x==2)

至于为什么会抛出特定的ValueError,我没有答案。