Christopher Ell
Christopher Ell

Reputation: 2048

Weird Error When Dividing two numbers in Pandas DataFrame

I am trying to divide two fields by each other below:

c1_preds_data['adj_final_price'] = (c1_preds_data["final_price "]/c1_preds_data['adjustment'])

In a Pandas DataFrame and am getting the below error message:

TypeError: ufunc 'true_divide' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

I have tried a df.dropna(), incase I am dividing by an N/A and I have tried checking that denominator doesn't have any zeros in it like below:

c1_preds_data.loc[c1_preds_data.adjustment == 0, 'adj_final_flag'] = -99
c1_preds_data.loc[c1_preds_data.adjustment != 0, 'adj_final_flag'] = 99

and they all came out as non-zero (99)

and am unsure about how to interpret the error message.

Upvotes: 6

Views: 47248

Answers (1)

Daniel Scott
Daniel Scott

Reputation: 985

You are trying to perform an operation on a string which is only acceptable for numerical types. (Perhaps from an sql database trying to preserve pip or point precision on your price data?)

If you want to preserve pip/point precision, you should consider storing the multiplier in a different table as an int and associating it with your exchange rate pair.

First, recast the series to float, then perform your operation.

c1_preds_data["final_price "] = c1_preds_data["final_price "].astype('float') c1_preds_data['adjustment'] = c1_preds_data['adjustment'].astype('float')

Looks like you are working on a parallel backtester. Good luck!

Upvotes: 13

Related Questions