Home > OS >  What should I do with this error? unsupported operand type(s) for /: 'str' and 'str&#
What should I do with this error? unsupported operand type(s) for /: 'str' and 'str&#

Time:11-09

I have database with name 'Data' :

#removing NULL from database
data_new2 = Data.copy()
data_new2.dropna(inplace = True)

then I did

#calculating deposit
data_new2list=['DATA6030','DATA6040']
data_new2['deposit']=data_new2[data_new2list].astype(float).sum(1)

data_new3=data_new2
data_new3['WFR']= data_new3['DATA9960']/data_new3['DATA6190']
data_new3['DR']=data_new3['deposit']/data_new3['DATA6190']`

However, I received this error:

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

CodePudding user response:

You are performing a division operation between two strings, convert your columns to make it work:

data_new2 = Data.copy().astype(float)

CodePudding user response:

The error is telling you that 'DATA9960' and 'DATA6190' columns contain at least one string each, and you can't divide two strings.

Assuming that those columns can contain non-numeric strings, first convert all the numeric strings to a numeric type, using pandas.to_numeric with errors='coerce'. The non-numeric strings will be set to NaN.

import pandas as pd

data_new2 = Data.copy()
data_new2.dropna(inplace=True)

data_new2list = ['DATA6030','DATA6040']
data_new2['deposit'] = data_new2[data_new2list].astype(float).sum(1)

#convert 'DATA9960', 'DATA6190' to numeric 
cols = ['DATA9960', 'DATA6190']
data_new2[cols] = data_new2[cols].apply(pd.to_numeric, errors='coerce')

# drop rows with NaN values in 'DATA9960', 'DATA6190' resulting from pd.to_numeric
data_new2.dropna(subset=cols, inplace=True)

# this doesn't return a copy btw. data_new3 and data_new2 point to the same object. 
# To make a copy you need data_new3 = data_new2.copy()
data_new3 = data_new2   

data_new3['WFR'] = data_new3['DATA9960'] / data_new3['DATA6190']
data_new3['DR'] = data_new3['deposit'] / data_new3['DATA6190']`
  • Related