使用pandas数据帧计算向前或向后

时间:2016-06-10 18:34:11

标签: python pandas dataframe

我想按周计算数据框架中的%差异,并将这些计算放在新的数据框中。

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

新数据框newdf如下所示:

index       Date     Zone   % diff
  0     2011-02-05  YQHDK    4.02
  1     2011-03-05  YQHDK    7.56

如何在不经过循环的情况下实现这一目标?

1 个答案:

答案 0 :(得分:3)

你可以这样做:

In [15]: df.Amount.pct_change()*100
Out[15]:
0         NaN
1    4.023256
2    7.556268
Name: Amount, dtype: float64

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