索引时无效的类型比较

时间:2017-04-30 22:20:35

标签: python pandas

我的数据框中有2列,目前设置如下:

   A          B
True      Morning
True      Morning
False     Morning
False     Morning

但希望B列在column A = False

时显示“下午”
A          B
True      Morning
True      Morning
False     Afternoon
False     Afternoon

但是,这会返回以下错误消息。有什么想法吗?

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

1 个答案:

答案 0 :(得分:1)

在您的A列中,数据类型似乎是??,但您要将其与字符串(bool)进行比较。删除引号,它应该工作正常。此外,您可能希望切换到"True"而不是.loc,因为它很快就会被弃用。

另请注意,当数据类型已为.ix时,您无需执行booldf['A']==True。您可以分别使用df['A']==Falsedf['A']

~df['A']