1
votes

I had put together the below code weeks ago and it was working as intended but now when I go back to run it i'm getting an error.

import pandas as pd
import numpy as np
file1 = "List - raw .csv"
df = pd.read_csv(file1)
pd.options.display.float_format = '{:,.2f}'.format 

df.loc[~df['Ship To Customer Zip'].str.contains('[A-Za-z]'), 'ZipCleaned'] = df['Ship To Customer Zip'].str.slice(stop=5)

Error: Traceback (most recent call last): File "", line 1, in File "C:\users...Python\Python37-32\lib\site-packages\pandas\core\generic.py", line 1541, in invert arr = operator.inv(com.values_from_object(self)) TypeError: bad operand type for unary ~: 'float'

The code was working as intended as of a few days ago. I also have back up code which I checked and it's generating the same error.

2

2 Answers

2
votes

1) Try updating pandas library c:/>pip install --upgrade pandas

2) There are NaN values... Try adding a parameter na=False

import pandas as pd
import numpy as np
file1 = "List - raw .csv"
df = pd.read_csv(file1)
pd.options.display.float_format = '{:,.2f}'.format 

df.loc[~df['Ship To Customer Zip'].str.contains('[A-Za-z]'), 'ZipCleaned', na=False] = df['Ship To Customer Zip'].str.slice(stop=5)
1
votes

What the error is saying is that you are using the bitwise unary operator ~ on a float value which it does not support.

In this case this float value is probably a NaN value

Are you sure that the data source (the csv file) wasn't changed ?

I tested with this

In [1]: import pandas as pd                                                     

In [2]: import numpy as np                                                      

In [3]: s1 = pd.Series(['Mouse', 'dog', 'house and parrot', '23', np.NaN])      

In [4]: s1.str.contains('og')                                                   
Out[4]: 
0    False
1     True
2    False
3    False
4      NaN
dtype: object

In [5]:  ~s1.str.contains('og', regex=False)                                    
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-9be2b1fdd8c9> in <module>
----> 1 ~s1.str.contains('og', regex=False)

~/tmp/test/venv/lib/python3.7/site-packages/pandas/core/generic.py in __invert__(self)
   1539     def __invert__(self):
   1540         try:
-> 1541             arr = operator.inv(com.values_from_object(self))
   1542             return self.__array_wrap__(arr)
   1543         except Exception:

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

In [6]: s1 = pd.Series(['Mouse', 'dog', 'house and parrot', '23'])              

In [7]: ~s1.str.contains('og', regex=False)                                     
Out[7]: 
0     True
1    False
2     True
3     True
dtype: bool

In [8]:  

Note that when I had the np.NaN in the series I got the same error as you did but when I removed it then it worked

So yeah, your code is fine, your data source changed