Python bad operand type

TypeError: bad operand type for unary ~: ‘NoneType’

In total, there are over 100,000 records and below is a value count of the response options for the PT_DISCH_DISPO variable:

HOME/SELF CARE OP 201253 PARENT HOME/SELF CARE IP 15313 Admitted as inpatient 13721 LEFT WITHOUT TREATMENT 4633 TRANS TO OTHER FACILITY OP 608 ERROR REGISTRATION 227 LEFT AGAINST MED ADVICE OP 181 DSCHRG/TRNSFR PSYCH IP 134 EXPIRED OTHER 64 EXPIRED NO AUTOPSY NEEDED 61 DISCH/TRANS to INPT REHAB FAC 33 TRANS TO ACUTE CARE HOSP IP 30 NO SHOW 27 EXPIRED W/ AUTOPSY 25 OTHER IP 24 RELATIVE HOME IP 19 TRANS TO ADULT FACILITY OP 13 LEFT AGAINST MED ADVICE IP 12 TRANSFERRED TO SNF IP 11 3RD PARTY PAYOR REQUEST FOR TRANS 10 EXPIRED/CORONER'S CASE 6 FOSTER HOME IP 5 HOME UNDER HOME HEALTH CARE IP 4 ORGANIZED GROUP HOME IP 4 REHABILITATION CENTER IP 3 DISCHARGED TO SNF OP 2 Against Medical Advice 2 CORRECTIONAL FACILITY IP 2 TRANS TO INTERMED CARE FAC IP 1 Expired other 1 DEAD ON ARRIVAL 1 
#removing strings from dataset "~" denotes do not keep TAT_v2 = TAT_v1[~TAT_v1.PT_DISCH_DISPO.str.contains("error|no show|left without treatment", case=False)] 

It runs fine when I pill data from say 2019 onward but when I expand my dataframe to include data from 2018 and run this line of code I get the following error:

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\generic.py in __invert__(self) 1540 def __invert__(self): 1541 try: -> 1542 arr = operator.inv(com.values_from_object(self)) 1543 return self.__array_wrap__(arr) 1544 except Exception: TypeError: bad operand type for unary ~: 'NoneType' 

Источник

Читайте также:  Код java the sims 3

TypeError: bad operand type for unary ~: ‘float’

(I made some edits to the original here in order to reflect what may appear in this very long dataframe). My goal here is to produce a unique ID for each of the values (ex. 1,2,8,9) associated to a question (ex. country_statis). I am attempting to concatenate country_satis to 1, so that all of my «blocks» have

0 Q2 country_satis . NaN NaN 1 NaN country_statis_1 . NaN NaN 2 NaN country_statis_2 . NaN NaN 3 NaN country_statis_8 . NaN NaN 4 NaN country_statis_9 . NaN NaN 5 NaN NaN . NaN NaN 
df.REFERENCE_CODE = df.REFERENCE_CODE.fillna('') df.REFERENCE_CODE.str.isnumeric().dtype # returns object headers = (df.REFERENCE_CODE != '') & ~df.REFERENCE_CODE.str.isnumeric() res = df.groupby(headers.cumsum())['REFERENCE_CODE'].apply(lambda x: x.iloc[0] + '_' + x) df.REFERENCE_CODE.update(res[df.REFERENCE_CODE.str.isnumeric()]) 

My goal here is also to keep the integrity and structure of the data, because eventually, ideally, I’d like to perform a clean merge of 2 data sources. I should probably do this in SQL lol. Error here:

Traceback (most recent call last): File "/Users/xx/Projects/trend_env/src/script4.py", line 10, in df.REFERENCE_CODE = df.REFERENCE_CODE.fillna('') File "/Users/xx/Projects/trend_env/lib/python3.7/site-packages/pandas/core/generic.py", line 5067, in __getattr__ return object.__getattribute__(self, name) AttributeError: 'DataFrame' object has no attribute 'REFERENCE_CODE' 
Traceback (most recent call last): File "/Users/xxx/Projects/trend_env/src/script4.py", line 16, in headers = (df.REFERENCE_CODE != '') & ~df.REFERENCE_CODE.str.isnumeric() File "/Users/xxx/Projects/trend_env/lib/python3.7/site-packages/pandas/core/generic.py", line 1466, in __invert__ Index(['Question number', 'REFERENCE_CODE', 'Filter', 'English stem', 'Translator note', 'Philippines - Bicolano', 'Philippines - Cebuano', 'Philippines - Ilonggo', 'Philippines Ilokano', 'Philippines - Tagalog', 'Unnamed: 10', 'Unnamed: 11', 'Unnamed: 12', 'Unnamed: 13'], dtype='object') arr = operator.inv(com.values_from_object(self)) TypeError: bad operand type for unary ~: 'float' 

EDIT2: As per Andy Hayden — do you mind helping me solve this logic.. I have the code working just fine. I have a case where the df looks like this:

25 partyfav_batt NaN 26 partyfav_bulgaria_GERB NaN 27 partyfav_bulgaria_BSP NaN 28 partyfav_bulgaria_DPS NaN 29 NaN 30 partyfav_bulgaria_DPS_1 NaN 31 partyfav_bulgaria_DPS_2 NaN 32 partyfav_bulgaria_DPS_3 NaN 33 partyfav_bulgaria_DPS_4 NaN 34 partyfav_bulgaria_DPS_8 NaN 35 partyfav_bulgaria_DPS_9 NaN 36 NaN 37 partyfav_batt NaN 38 partyfav_canada_Lib NaN 39 partyfav_canada_Cons NaN 40 partyfav_canada_NDP NaN 41 NaN 42 partyfav_canada_NDP_1 NaN 43 partyfav_canada_NDP_2 NaN 44 partyfav_canada_NDP_3 NaN 45 partyfav_canada_NDP_4 NaN 46 partyfav_canada_NDP_8 NaN 47 partyfav_canada_NDP_9 NaN 
37 partyfav_batt NaN 38 partyfav_canada_Lib NaN 39 partyfav_canada_Cons NaN 40 partyfav_canada_NDP NaN 
39 partyfav_canada_Cons NaN 40 partyfav_canada_NDP NaN 41 NaN 42 partyfav_canada_Cons_1 NaN 43 partyfav_canada_Cons_2 NaN 44 partyfav_canada_Cons_3 NaN 45 partyfav_canada_Cons_4 NaN 42 partyfav_canada_NDP_1 NaN 43 partyfav_canada_NDP_2 NaN 44 partyfav_canada_NDP_3 NaN 45 partyfav_canada_NDP_4 NaN 

Источник

Читайте также:  Таблицы

TypeError: bad operand type for unary -: ‘str’

I’ve got a problem with Python 2.7.3-32bits on Windows. I put this code to see if anyone can help me out with this error. The comments are in Spanish but it don’t affect the code.

 import gtk import numpy import math import os #Pedimos el nombre de la imagen de origen nombreFich = input("Por favor, introduzca el nombre de la imagen de origen:") #Validar que existe el fichero imagen1 = gtk.Image() imagen1.set_from_file('C:\\Users\\xxx\\Desktop\\xxxx.png') pb1 = imagen1.get_pixbuf() pm1 = pb1.get_pixels_array() #Hacemos una copia de la imagen pm2 = pm1.copy() #Validamos los puntos de distorsion hasta que sean validos puntos = " " arrayPuntos = " " while(puntos == " " and len(arrayPuntos) < 4): print"Por favor, introduzca los puntos de distorsión xc yc r e:" puntos= raw_input() arrayPuntos = puntos.split(" ") #Sacamos los puntos separando la cadena por el caracter espacio xc =(puntos[0]) yc =(puntos[1]) r =(puntos[2]) e =(puntos[3]) #función que calcula el grado de distorsión def grado(self,z,e): if(z>1): return 1 elif(e<0): return (1/z)**(-e/(1-e)) else: return z**e #Distorsionamos la imagen def distors(xc,yc,r,e,x,y): d = math.sqrt(x**2+y**2)#Sacamos la distancia z = d/r if(z!=0): g=grado(z,e) xm=x*g ym=y*g return xm,ym else: xm=x ym=y return xm,ym def recorrido (pm1, xc, yc, r, e): pm2 = pm1.copy() x= str(--r) y= str(--r) while (y <= r): while (x <= r): xm, ym = mover(xc, yc, r, e, x, y) pm2[yc+y][xc+x] = pm1[yc+ym][xc+xm] x = x+1 y= y+1 x= -r return pm2 pm2 = recorrido(pm1, xc, yc, r, e) #Guardamos los cambios pb2 = gtk.gdk.pixbuf_new_from_array(pm2,pb1.get_colorspace(),pb1.get_bits_per_sample()) nomfich2 = nombreFich+"_copia" ext = os.path.splitext("C:\\Users\xxx\Desktop\xxxx.png_copia")[1][1:].lower() pb2.save("C:\\Users\xxx\Desktop\xxxx.png_copia",ext) print"FINISH" 
 Traceback (most recent call last): File "F:\Dropbox\Práctica Pitón\Práctica3.0.py", line 71, in pm2 = recorrido(pm1, xc, yc, r, e) File "F:\Dropbox\Práctica Pitón\Práctica3.0.py", line 59, in recorrido x= str(--r) TypeError: bad operand type for unary -: 'str' 

2 Answers 2

The error message is telling you that r is a string. You can't negate a string.

Why is it a string? Well, it seems to come from here:

# . puntos= raw_input() arrayPuntos = puntos.split(" ") # . r =(puntos[2]) 

The split method on a string returns a list of strings.

So, how do you solve this? Well, if r is, say, the string "22", then float(r) is the float 22.0 , and int(r) is the integer 22 . One of those is probably what you want.

Once you add, say, r=int(r) , your --r will no longer be an exception.

But it probably isn't what you want. In Python, --r just means the negation of the negation of r —in other words, it's the same as -(-(r)) , which is just r . You're probably looking for the equivalent of the C prefix operator -- , which decrements the variable and returns the new value. There is no such operator in Python; in fact, there are no operators that modify a variable and then return the value.

This is part of a larger issue. Python is designed to make statements and expressions as distinct as possible, to avoid confusion. C is designed to make as many things as possible expressions, to save typing. So, you often can't just translate one into the other line by line.

In this case, you have to do it in two steps, as Thanasis Petsas shows:

Источник

Python bad operand type

Last updated: Jul 2, 2023
Reading time · 4 min

banner

# Table of Contents

# TypeError: bad operand type for unary +: 'str' [Solved]

The Python "TypeError: bad operand type for unary +: 'str'" and "TypeError: bad operand type for unary -: 'str'" errors occur when you try to use the unary + or - operators with a string.

To solve the error, convert the value to an integer or a float by using the int() or float() class or correct the assignment.

Here is an example of how the error occurs.

Copied!
a_str = 'bobbyhadz' a_str = +'123' # ⛔️ TypeError: bad operand type for unary +: 'str' print(a_str)

type error bad operand type for unary str

And here is another example.

Copied!
a_str = '105' new_str = +a_str # ⛔️ TypeError: bad operand type for unary +: 'str' print(new_str)

We are trying to use the unary + operator with a string which is not allowed.

You might also get the error when using the unary - operator.

Copied!
a_str = '105' new_str = -a_str # ⛔️ TypeError: bad operand type for unary -: 'str' print(new_str)

# Convert the value to an integer or float before using the unary + and - operators

One way to solve the error is to convert the value to an integer or a floating-point number before using the unary + and - operators.

Copied!
a_str = '105' new_str = +int(a_str) print(new_str)

convert the value to integer or float before using unary plus

The code sample uses the int class to convert the value to an integer before using the unary plus operator.

You can also convert the value to a floating-point number before using the operator.

Copied!
a_str = '105.123' new_str = +float(a_str) print(new_str) # 👉️ 105.123

convert the value to integer or float before using unary plus

We used the float class to convert the string to a floating-point number before using the unary + operator.

The same approach can be used to solve the "TypeError: bad operand type for unary -: 'str'" error.

Copied!
a_str = '105' new_str = -int(a_str) print(new_str) # 👉️ -105

convert-to-int-before-using-unary-minus

# Correct your assignments when concatenating strings

The error is also raised when you have an incorrect assignment when concatenating strings.

Copied!
a_str = 'bobbyhadz' a_str = +'123' # ⛔️ TypeError: bad operand type for unary +: 'str' print(a_str)

We tried to append the string "123" to the string "bobbyhadz" , however, the plus should be placed to the left of the equal sign = .

Copied!
a_str = 'bobbyhadz' a_str += '123' print(a_str) # 👉️ bobbyhadz123

move plus to left of equal sign

The expression a_str += 'abc' is equivalent to a_str = a_str + 'abc' .

Copied!
a_str = 'bobbyhadz' a_str += '123' print(a_str) # 👉️ bobbyhadz123 # Same as above new_str = 'bobbyhadz' new_str = new_str + '123' print(new_str) # 👉️ bobbyhadz123

equivalent assignments

# Using + to concatenate strings

If you meant to use the unary + operator to concatenate strings, use the following syntax.

Copied!
first = 'bobby' last = 'hadz' full_name = first + ' ' + last print(full_name) # bobby hadz

using unary plus to concatenate strings

The unary + operator is used between two strings.

You can also use a formatted string literal to achieve the same result.

Copied!
first = 'bobby' last = 'hadz' full_name = f'first> last>' print(full_name) # bobby hadz

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f .

Make sure to wrap expressions in curly braces - .

# Use a backslash \ when concatenating multiline strings

Make sure to use a backslash when concatenating multiline strings.

Copied!
first = 'bobby' last = 'hadz' full_name = first \ + ' ' + last print(full_name) # 👉️ bobby hadz

The \ backslash character is used as a line continuation character and instructs Python that the expression continues on the next line.

Alternatively, you can use parentheses () .

Copied!
first = 'bobby' last = 'hadz' full_name = (first + ' ' + last ) print(full_name) # 👉️ bobby hadz

Either approach works, but using parentheses is a bit easier to read.

# Using print() incorrectly

The error also occurs when you use the print() function incorrectly.

Copied!
first = 'bobby' last = 'hadz' # ⛔️ TypeError: bad operand type for unary +: 'str' print(first, + last)

We are trying to use the unary + operator with a string.

Notice that we have a comma , and a plus + sign.

To solve the error, we either have to remove the comma or the + sign.

Copied!
first = 'bobby' last = 'hadz' print(first, last) # 👉️ bobby hadz print(first + last) # 👉️ bobbyhadz

# The input() function always returns a string

Note that the input() function always returns a string.

You have to use the int() class to convert the string to an integer when taking integer user input.

Copied!
num = int(input('Enter a number: ')) if num > 10: print(num) else: print(-num)

We used the int() class to convert the input string to an integer but you can also use the float() class if you need to convert the value to a floating-point number.

We are no longer trying to use the unary - operator with a string, so the error is resolved.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оцените статью