Reputation: 1690
I want to calculate % differences in a dataframe by week, and put those calculations in a new dataframe.
Start with df
:
index Date Zone Amount
0 2011-01-08 YQHDK 1691938000.0
1 2011-02-05 YQHDK 1760009000.0
2 2011-03-05 YQHDK 1893000000.0
New dataframe newdf
would look like:
index Date Zone % diff
0 2011-02-05 YQHDK 4.02
1 2011-03-05 YQHDK 7.56
How can I achieve this without going through a loop?
Upvotes: 0
Views: 1598
Reputation: 210922
you can do it this way:
In [15]: df.Amount.pct_change()*100
Out[15]:
0 NaN
1 4.023256
2 7.556268
Name: Amount, dtype: float64
or
In [16]: df.Amount.pct_change().shift(-1)*100
Out[16]:
0 4.023256
1 7.556268
2 NaN
Name: Amount, dtype: float64
In [8]: df['pct_diff'] = df.Amount.pct_change()*100
In [9]: df
Out[9]:
index Date Zone Amount pct_diff
0 0 2011-01-08 YQHDK 1.691938e+09 NaN
1 1 2011-02-05 YQHDK 1.760009e+09 4.023256
2 2 2011-03-05 YQHDK 1.893000e+09 7.556268
Upvotes: 3