nerd_gram
nerd_gram

Reputation: 53

TypeError: unsupported operand type(s) for +: 'int' and 'str' - Pandas DataFrame

addition add-revised
6 insertions(+) 6
NaN 0
8 insertions(+) 8

From the 'addition' column of the data frame, I created the 'add-revised' column.


df['add-revised'] = df.addition.str.extract('(\d+)')
df['add-revised'] = df['add-revised'].fillna(0)

When I attempt to do


df_new['add-revised'].mean()

It's giving me the following error

TypeError: unsupported operand type(s) for +: 'int' and 'str'

I attempted to solve the problem with

df_new['add-revised'].to_numeric()

and it's giving me the following error

AttributeError: 'Series' object has no attribute 'to_numeric'

Upvotes: 0

Views: 1290

Answers (2)

mahmoud lotfi
mahmoud lotfi

Reputation: 21

The easiest way to apply the built-in function astype('int'), but this function can't handle errors during type conversion.

The best way is to create a custom function to handle the error during conversion process:

def try_convert_int(x):   
    try:
        x = int(x)
    except:
        x = np.nan                
    return x

Applying the function to df:

df_new['add-revised'] = df_new.apply(lambda x: try_convert_int(x['add-revised']), axis=1)

Upvotes: 0

Bugface
Bugface

Reputation: 313

Did you try:

df_new['add-revised'] = df_new['add-revised'].astype(int)

it works for pandas version '1.2.0'

Upvotes: 1

Related Questions