简体   繁体   English

使用pandas计算两个特定行之间的百分比变化

[英]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). 我想添加一个索引名为'percChane'的新行,它计算第一行和最后一行之间的perc变化(在本例中为May和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()? 可以使用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: 或者,您可以调用pct_change让pandas为您执行此操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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