Craig
Craig

Reputation: 1985

Pandas - percent difference within column

This is closely related to this question - but I would like to find the % difference based on the previous row and not the first row as in the example.

So my input would be

security    date        price
IBM         1/1/2016    100
IBM         1/2/2016    102
IBM         1/3/2016    108
AAPL        1/1/2016    1000
AAPL        1/2/2016    980
AAPL        1/3/2016    1050
AAPL        1/4/2016    1070

And my resultant output would be

security    date        price   change
IBM         1/1/2016    100     NA
IBM         1/2/2016    102     2%
IBM         1/3/2016    108     5.8%
AAPL        1/1/2016    1000    NA
AAPL        1/2/2016    980     -2%
AAPL        1/3/2016    1050    7.14%
AAPL        1/4/2016    1070    1.9%

Upvotes: 0

Views: 886

Answers (2)

BENY
BENY

Reputation: 323226

We using pct_change

df.groupby('security').price.pct_change()
Out[1393]: 
0         NaN
1    0.020000
2    0.058824
3         NaN
4   -0.020000
5    0.071429
6    0.019048
Name: price, dtype: float64

Upvotes: 4

Bharath M Shetty
Bharath M Shetty

Reputation: 30605

Use groupby diff()/shift() * 100 i.e

g = df.groupby('security')['price']

df['new'] = (g.diff()/g.shift())*100

  security      date  price       new
0      IBM  1/1/2016    100       NaN
1      IBM  1/2/2016    102  2.000000
2      IBM  1/3/2016    108  5.882353
3     AAPL  1/1/2016   1000       NaN
4     AAPL  1/2/2016    980 -2.000000
5     AAPL  1/3/2016   1050  7.142857
6     AAPL  1/4/2016   1070  1.904762

Upvotes: 2

Related Questions