Pandas 之前 n 值的百分比变化

Pandas percentage change to a n value before

您好,我有一个包含 n 个值的 pandas 列

2018-01-03 01:30:00  14873.46  
2018-01-03 01:45:00  14848.01  
2018-01-03 02:00:00  14888.90  
2018-01-03 02:15:00  14834.59  
2018-01-03 02:30:00  14895.08  
2018-01-03 02:45:00  15049.98  
2018-01-03 03:00:00  15041.00  
2018-01-03 03:15:00  15198.00 

我想获取与 n 组的第一个值相关的百分比变化数组。 比如我选了一组三个,

2018-01-03 01:30:00  14873.46  
2018-01-03 01:45:00  14848.01  
2018-01-03 02:00:00  14888.90 

2018-01-03 01:45:00  14848.01  
2018-01-03 02:00:00  14888.90  
2018-01-03 02:15:00  14834.59  

对于这套我想退货

  #This is percentage change between all values of the set and the first value of the same set ex (14848.01 and 14873.46) and (14888.90 and 14873.46), 
     [-0.17,0.10]
     [0.27,-0.09]

如何使用 pandas

获取它?

取决于您希望它如何呈现。但这是一种方式:

pd.concat([
    df.pct_change().shift(-1),
    df.pct_change(2).shift(-2)
], axis=1, keys=['Shift1', 'Shift2'])

                       Shift1    Shift2
                         ColA      ColA
Date                                   
2018-01-03 01:30:00 -0.001711  0.001038
2018-01-03 01:45:00  0.002754 -0.000904
2018-01-03 02:00:00 -0.003648  0.000415
2018-01-03 02:15:00  0.004078  0.014519
2018-01-03 02:30:00  0.010399  0.009797
2018-01-03 02:45:00 -0.000597  0.009835
2018-01-03 03:00:00  0.010438       NaN
2018-01-03 03:15:00       NaN       NaN

@piRSquared 在这种情况下的回答是正确的。

然而,这个问题也让我开始思考如何将一个系列或数组拆分成重叠的块。

import numpy as np
import pandas as pd

def rolling(a, window):
    shape = (a.size - window + 1, window)
    strides = (a.itemsize, a.itemsize)
    return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)

a = np.array(["14873.46", "14848.01", "14888.90", "14834.59", "14895.08",
              "15049.98", "15041.00", "15198.00"])
df = pd.DataFrame(rolling(a, 3))
df.columns = ['first', 'second', 'third']
print(df)

      first    second     third
0  14873.46  14848.01  14888.90
1  14848.01  14888.90  14834.59
2  14888.90  14834.59  14895.08
3  14834.59  14895.08  15049.98
4  14895.08  15049.98  15041.00
5  15049.98  15041.00  15198.00

有关将数组拆分为重叠块的更多详细信息,请参阅 this answer

Pandas' pct_change() 函数根据前面的值而不是第一个值进行计算,这是@piRSquared(使用 shift())接受的答案是的另一个原因正确答案。