state | var1 | var2 | var3 | var4 |
---|---|---|---|---|
1 | 36 | 6 | 5 | (T) |
2 | 46 | 2 | 3 | 7 |
3 | 42 | 12 | (D) | 9 |
I want to write a code dividing each cell from the var2 to var4 by var1 (row by row). While doing so, how to ignore (D) and (T) which are not integers on the dataframe?
I tried the code below but it casts an error "TypeError: unsupported operand type(s) for /: 'str' and 'str'".
Help appreciated!
df.iloc[:,2:4].div(df.iloc[:,1], axis = 0)
CodePudding user response:
Try this :
df.apply(pd.to_numeric, errors = 'coerce')
CodePudding user response:
your code would have helped a little. anyways use exception handling. try this
try:
df.iloc[:,2:4].div(df.iloc[:,1], axis = 0)#or whatever your code is
except TypeError:
continue #what you want to do if a d or t comes
i have used continue
guessing you are using some form of loop as this will only work with one element at a time or skip out entire rows or matrix in which error occurs.