简体   繁体   中英

calculate percentage for the data at the end in pandas

I need to calculate profit/loss percentage for closing prices over the given n days. df is the data frame. Close Price is the closing price

def profit_loss(days):
    last = df[-1:]['Close Price']
    begin = df[-days:-(days-1)]['Close Price']
    return ((last-begin)/last)*100

the function is supposed to given the required percentage. If the days are given, the function takes the last day closing price and the last nth day closing price and calculate the profit/loss percentage. My output is giving me NaN as output

profit_loss(7)

The output is;

487   NaN
493   NaN
Name: Close Price, dtype: float64

The expected output is -0.0102 . The closing price data for the last 7 days is

[970.20,981.75,979.95,980.50,980.45,975.35,979.10]

I believe the reason you are getting NaN values your your output is because the last and begin variables are of type Series . Try adding .item() , which will return the float values.

last = df[-1:]['Close Price'].item()
begin = df[-days:-(days-1)]['Close Price'].item()

Instead of slicing your data in order to get a single element (which gives you Series , as Kurt Kline pointed out), you should simply get the element of interest:

def profit_loss(days):
    last = df['Close Price'][-1]
    begin = df['Close Price'][-days]
    return ((last-begin)/last)*100

This also fixes a bug: in the original code, if days =1, then you take Close Prices for days [-1:0] , which is no day at all—since this slice starts from the last element (-1) and tries to go down to the first element (0).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM