TypeError: bad operand type for unary ~: float

PythonPandas

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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)]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionfredleyView Question on Stackoverflow
Solution 1 - PythonjezraelView Answer on Stackoverflow
Solution 2 - Pythonaryan aryanView Answer on Stackoverflow