TAGS :Viewed: 8 - Published at: a few seconds ago

[ Typecasting before division (or any other mathematical operator) of columns in dataframes ]

I have a dataframe with columns A, B. I need to add a column C which is basically the division of entries in A by the entries in B.

I tried this:

df['C'] = df['A'] / df['B']

But I need to convert to double or float before I do this. How should I type-cast the dtype of the columns?

Thanks.

Answer 1


How about

df['C'] = df['A'] * 1.0 / df['B']

Answer 2


Or this:

df['C'] = df['A'].astype('float') / df['B']