[英]Invalid type comparison when indexing
I have 2 columns in my dataframe currently set like this: 我的数据框中目前有2列设置为:
A B
True Morning
True Morning
False Morning
False Morning
But would like column B to show "Afternoon" when column A = False
但是希望当
column A = False
时B列显示“下午”
A B
True Morning
True Morning
False Afternoon
False Afternoon
However this returns the following error message. 但是,这将返回以下错误消息。 Any ideas?
有任何想法吗?
df = mask.ix[mask["A"] == "True" , "B"] = "Afternoon"
Anaconda3\lib\site-packages\pandas\core\ops.py:792: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
result = getattr(x, name)(y)
Traceback (most recent call last):
File "<ipython-input-130-f98341f5041b>", line 1, in <module>
df = mask.ix[mask["A"] == "True" , "B"] = "Afternoon"
File "Anaconda3\lib\site-packages\pandas\core\ops.py", line 855, in wrapper
res = na_op(values, other)
File "Anaconda3\lib\site-packages\pandas\core\ops.py", line 794, in na_op
raise TypeError("invalid type comparison")
TypeError: invalid type comparison
It seems in your column A, the data type is bool
but you are comparing it against a string ( "True"
). 似乎在您的A列中,数据类型为
bool
但您正在将其与字符串( "True"
)进行比较。 Remove the quotation marks and it should work fine. 删除引号,它应该可以正常工作。 Also, you may want to switch to
.loc
instead of .ix
as it will be deprecated soon. 另外,您可能希望切换到
.loc
而不是.ix
因为它将很快弃用。
Also note that when the data type is already bool
, you don't need to do df['A']==True
or df['A']==False
. 还要注意,当数据类型已经为
bool
,您无需执行df['A']==True
或df['A']==False
。 You can just use df['A']
and ~df['A']
respectively. 您可以分别使用
df['A']
和~df['A']
。
df.loc[~df['A'], 'B'] = 'Afternoon'
df
Out:
A B
0 True Morning
1 True Morning
2 False Afternoon
3 False Afternoon
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.