Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 428
Christopher Ell Avatar asked Feb 27 '19 05:02

Christopher Ell


People also ask

How do you divide two numbers in pandas?

Method 2: Pandas divide two columns using div() function It divides the columns elementwise. It accepts a scalar value, series, or dataframe as an argument for dividing with the axis. If the axis is 0 the division is done row-wise and if the axis is 1 then division is done column-wise. Execute the below lines of code.

How do you divide numbers in a DataFrame in Python?

div() method divides element-wise division of one pandas DataFrame by another. DataFrame elements can be divided by a pandas series or by a Python sequence as well. Calling div() on a DataFrame instance is equivalent to invoking the division operator (/).

How do you do division in pandas?

In the pandas series constructor, the div() or divide() method is used to perform element-wise floating division operation between the two series objects or between a series and a scalar. The method returns a series with resultant floating division values.

How do I divide two columns in pandas?

The simple division (/) operator is the first way to divide two columns. You will split the First Column with the other columns here. This is the simplest method of dividing two columns in Pandas. We will import Pandas and take at least two columns while declaring the variables.


1 Answers

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!

like image 121
Daniel Scott Avatar answered Oct 02 '22 22:10

Daniel Scott