Multiplication of two pandas fields

I have a dataframe with a list of transactions, and I would like to take the exec_price field and multiply it by the size field to get the total cost.

So, I would like to add a new field: cost = exec_price * size

                            date security action  size   ask_price exec_price  \
order_id                                                                    
188      2016-10-24 10:04:44     AAPL    buy     5  116.599998     117.44   
189      2016-10-24 10:04:44     NFLX    buy     5       127.5      128.4   
190      2016-10-24 10:04:44      AMD    buy     5        6.52       6.65   

          status  
order_id          
188       filled  
189       filled  
190       filled  

When I try to execute several using:

transactions['cost'] = transactions['exec_price'] * transactions['size']

I get this:

                        date security action  size   ask_price exec_price  \
order_id                                                                    
188      2016-10-24 10:04:44     AAPL    buy     5  116.599998     117.44   
189      2016-10-24 10:04:44     NFLX    buy     5       127.5      128.4   
190      2016-10-24 10:04:44      AMD    buy     5        6.52       6.65   

          status                            cost  
order_id                                          
188       filled  117.44117.44117.44117.44117.44  
189       filled       128.4128.4128.4128.4128.4  
190       filled            6.656.656.656.656.65  

Does anyone know how I can fix this?

Thanks in advance.

+4
source share
1 answer

This is because it strchanges it to float with astype:

transactions['exec_price'] = transactions['exec_price'].astype(float)

or safer use to_numericto handle any duff values:

transactions['exec_price'] = pd.to_numeric(transactions['exec_price'], errors='coerce')

When you multiply the column str, it just repeats the contents of the row using this scalar value

+5

Source: https://habr.com/ru/post/1658702/


All Articles