熊猫:groupby不能正确计算pct_change

时间:2019-05-29 19:28:51

标签: python pandas

我的数据是:

>>> prices = pandas.DataFrame(
{"StkCode":["StockA","StockA","StockA","StockA","StockA","StockB","StockB","StockB","StockB","StockB","StockC","StockC","StockC","StockC","StockC",], 
"Price":[1035.23, 1032.47, 1011.78, 1010.59, 1016.03, 1007.95, 1022.75, 1021.52, 1026.11, 1027.04, 1030.58, 1030.42, 1036.24, 1015.00, 1015.20]}
)

哪个给:

      Price StkCode
0   1035.23  StockA
1   1032.47  StockA
2   1011.78  StockA
3   1010.59  StockA
4   1016.03  StockA
5   1007.95  StockB
6   1022.75  StockB
7   1021.52  StockB
8   1026.11  StockB
9   1027.04  StockB
10  1030.58  StockC
11  1030.42  StockC
12  1036.24  StockC
13  1015.00  StockC
14  1015.20  StockC

然后,我打电话给

>>> prices["Return"] = prices.groupby("StkCode")["Price"].pct_change(1)

我希望:

      Price StkCode    Return
0   1035.23  StockA       NaN
1   1032.47  StockA -0.002666
2   1011.78  StockA -0.020039
3   1010.59  StockA -0.001176
4   1016.03  StockA  0.005383
5   1007.95  StockB       NaN
6   1022.75  StockB  0.014683
7   1021.52  StockB -0.001203
8   1026.11  StockB  0.004493
9   1027.04  StockB  0.000906
10  1030.58  StockC       NaN
11  1030.42  StockC -0.000155
12  1036.24  StockC  0.005648
13  1015.00  StockC -0.020497
14  1015.20  StockC  0.000197

但是,我实际上得到了:

    Price   StkCode Return
0   1035.23 StockA  NaN
1   1032.47 StockA  -0.002666
2   1011.78 StockA  -0.020039
3   1010.59 StockA  -0.001176
4   1016.03 StockA  0.005383
5   1007.95 StockB  -0.007953
6   1022.75 StockB  0.014683
7   1021.52 StockB  -0.001203
8   1026.11 StockB  0.004493
9   1027.04 StockB  0.000906
10  1030.58 StockC  0.003447
11  1030.42 StockC  -0.000155
12  1036.24 StockC  0.005648
13  1015.00 StockC  -0.020497
14  1015.20 StockC  0.000197

似乎正在为StockB和StockC的第一个实例计算收益。

我正在使用Python 2.7。我的代码是否有问题,无视groupby?

谢谢!

1 个答案:

答案 0 :(得分:0)

DataFrame的loc方法将正确应用这些值:

prices.loc[:, 'Return'] = prices.groupby("StkCode")["Price"].pct_change(1)

    Price   StkCode Return
0   1035.23 StockA  NaN
1   1032.47 StockA  -0.002666
2   1011.78 StockA  -0.020039
3   1010.59 StockA  -0.001176
4   1016.03 StockA  0.005383
5   1007.95 StockB  NaN
6   1022.75 StockB  0.014683
7   1021.52 StockB  -0.001203
8   1026.11 StockB  0.004493
9   1027.04 StockB  0.000906
10  1030.58 StockC  NaN
11  1030.42 StockC  -0.000155
12  1036.24 StockC  0.005648
13  1015.00 StockC  -0.020497
14  1015.20 StockC  0.000197