![](/img/trans.png)
[英]How to replace values in multiple categoricals in a pandas DataFrame
[英]Pandas DataFrame with categoricals fails comparison
比較沒有分類列的數據框:
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
您可以使用DataFrame方法套用,它將一個函數應用於框架的所有元素。 當變量是分類變量時,以下行有效:
df.apply(lambda x: x==2)
至於為什么拋出那個特定的ValueError
,我沒有答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.