Skip to main content
 首页 » 编程设计

python之在 pandas 中添加一列,即回溯 x 行的最大值

2024年09月07日9小虾米

我的原始数据框是这样的:

   Date  Price 
0     0    100 
1     1     10 
2     2     30 
3     3     20 
4     4     50 

价格是 float 的。

我需要能够添加一个“最近 x 天的最大值”的列,包括今天 到原始数据框。

结果应该是 x=3

  Date   Price   Max_3Days 
    0      100    N/A 
    1      10     N/A 
    2      30     100 
    3      20     30 
    4      50     50   

请您参考如下方法:

假设这是您的输入,

df 
 
   Date  Price 
0     0    100 
1     1     10 
2     2     30 
3     3     20 
4     4     50 

您可以通过滚动最大值来完成此操作。

df.Price.rolling(3).max() 
 
0      NaN 
1      NaN 
2    100.0 
3     30.0 
4     50.0 
Name: Price, dtype: float64 

或者,如果您真的想要 N/A 而不是 NaN,从而通过混合字符串和对象来破坏性能,请链接一个 fillna 调用之后。

df.Price.rolling(3).max().fillna('N/A') 
 
0    N/A 
1    N/A 
2    100 
3     30 
4     50 
Name: Price, dtype: object 

注意!我不经常提及旧版本的 API,但对于 0.17 及以下版本,有 pd.rolling_max -

pd.rolling_max(df.Price, window=3) 
 
0      NaN 
1      NaN 
2    100.0 
3     30.0 
4     50.0 
Name: Price, dtype: float64 

在最新版本中已弃用,请改用 pd.Series.Rolling.max。