简体   繁体   中英

Invalid type comparison when indexing

I have 2 columns in my dataframe currently set like this:

   A          B
True      Morning
True      Morning
False     Morning
False     Morning

But would like column B to show "Afternoon" when column A = False

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" ). 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.

Also note that when the data type is already bool , you don't need to do df['A']==True or df['A']==False . You can just use df['A'] and ~df['A'] respectively.

df.loc[~df['A'], 'B'] = 'Afternoon'

df
Out: 
       A          B
0   True    Morning
1   True    Morning
2  False  Afternoon
3  False  Afternoon

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM