简体   繁体   中英

Calculate the percentage change between two specific rows with pandas

I have a dataframe like so:

         AAPL      MSFT
May       200       120
Jun       190       122
Jul       170       127
Aug       180       135

I want to add a new row with index name 'percChane' that calculates the perc change bwtween the first and last row (in this example May and Aug).

             AAPL      MSFT
    May       200       120
    Jun       190       122
    Jul       170       127
    Aug       180       135
   percChng   -10      12.5

Can this be done using df.pct_change()? If not whats the most efficient way to do this - it always needs to be the first and last row.

You can pick out the rows you want to calculate the % change for, then calculate it yourself:

s, e = df.iloc[0], df.iloc[-1]
df = df.append(((e - s) / s * 100).rename('percChng'))
df
           AAPL   MSFT
May       200.0  120.0
Jun       190.0  122.0
Jul       170.0  127.0
Aug       180.0  135.0
percChng  -10.0   12.5

Alternatively, you can call pct_change to have pandas do it for you:

df = df.append(df.iloc[[0, -1]].pct_change().iloc[-1].mul(100).rename('percChng'))
df
           AAPL   MSFT
May       200.0  120.0
Jun       190.0  122.0
Jul       170.0  127.0
Aug       180.0  135.0
percChng  -10.0   12.5

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