76
df = df[~df["column"].str.contains("Total")]

TypeError: bad operand type for unary ~: 'float'

Why does .str.contains() return a float? What should I be doing here?

3
  • what is the out put for df["column"].dtypes
    – BENY
    Sep 12, 2018 at 14:37
  • @kindall Oh so it's just operator precedence? I'll try df[~(df["column"].str.contains("Total"))]
    – fredley
    Sep 12, 2018 at 14:40
  • 1
    After some testing that doesn't seem to be the case, sorry for the red herring.
    – kindall
    Sep 12, 2018 at 15:07

2 Answers 2

161

I think there are NaNs values, so need specify parameter na:

df = pd.DataFrame({
    'column': ['Total','a',np.nan],
    'B': list(range(3))
})
print (df)
  column  B
0  Total  0
1      a  1
2    NaN  2

df = df[~df["column"].str.contains("Total", na=False)]
print (df)
  column  B
1      a  1
2    NaN  2
2
  • 1
    I have the same error, and I'm basically using .contains on a specific column of my df. I chcked it, and it does not have any NaN's. I added the na=False, and the error disappears. How could I explain the error I get, even though the column I am working with is a string with no NaNs? So I am using this line: df_main = df_main[~df_main['Category'].str.contains('|'.join(searchfor))], where searchfor is a list of words. Doing this generates the error
    – Alex Ruiz
    Jul 21, 2021 at 18:36
  • Okay, so I solved my problem. It was a faulty source of my csv file. I hadn't cleared all cells, so pandas was taking some of them as NaN.
    – Alex Ruiz
    Jul 21, 2021 at 19:03
3

In this type, we will see that we have some column values that are nan or empty so we were not able to do this. Hence, when you applied the code as here given below it, will work.

df_pcc_mod = df_pcc_mod[~df_pcc_mod['Invoice'].str.contains('Reversed',na=False)]
1
  • TypeError: bad operand type for unary ~: 'float' Sep 8, 2021 at 5:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.