Weird Error When Dividing two numbers in Pandas DataFrame
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!
Related videos on Youtube
Christopher Ell
Updated on July 14, 2022Comments
-
Christopher Ell almost 2 years
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.
-
Christopher Ell about 5 yearsThanks, converting it worked. Can't believe I didn't try that I had the same issue earlier with this data, but a different error message.
-
Daniel Scott about 5 yearsAre you storing the prices as strings so that you preserve pip precision?
-
Christopher Ell about 5 yearsNo, I was importing it from a large text file where they were stored as monetary values with $ and , and so when Pandas was importing them they were importing as text. The file was too large to be reformatted in Excel.