这是我的DataFrame:

import pandas as pd
df = pd.DataFrame({'a': [150, 106, 119, 131, 121, 140, 160, 119, 170]})

这是预期的输出.我想创建第b列:

     a      b
0  150      140
1  106      160
2  119      160
3  131      161 
4  121      NaN
5  140      NaN
6  160      NaN
7  119      NaN
8  170      NaN

我想要在滚动窗口6中获得最大值.但是,我想忽略每个窗口的第一个值.

在这张图片中,我展示了我想要的窗口.红色单元格是应该从计算中排除的单元格,绿色单元格是窗口的最大值,单位为b.

enter image description here

我更喜欢一般的解决方案.例如,忽略每个窗口的前N个值后得到max().

以下是我的一些try ,但没有奏效:

# attempt 1
df['b'] = df.a.shift(-1).rolling(6).max()
# attempt 2
df['b'] = df.a.rolling(6, closed='left').max()
# attempt 3 
for i in range(3):
    x = df.iloc[i+1:i+6]

推荐答案

天真的做法是用groupby.transform来代替第一项:

N = 6
df['out'] = df.loc[::-1, 'a'].rolling(N).apply(lambda x: x.iloc[:-1].max())

但是,由于您的运算与此值无关,因此最好在事后计算N-1shift上的rolling.max.这可以将代码简化为:

N = 6
df['out'] = df.loc[::-1, 'a'].rolling(N-1).max().shift()

Note that since 100 uses the 102 values by default, we need to first 103 the order of the Series with 101.

输出:

     a    out
0  150  140.0
1  106  160.0
2  119  160.0
3  131  170.0
4  121    NaN
5  140    NaN
6  160    NaN
7  119    NaN
8  170    NaN

generalization

要概括为跳过skip个值,请执行以下操作:

N = 6
skip = 2

df['out'] = df.loc[::-1, 'a'].rolling(N-skip).max().shift(skip)

示例(为清楚起见,将第二个119更改为118):

     a  skip=0  skip=1  skip=2  skip=3  skip=4  skip=5  skip=6
0  150   150.0   140.0   140.0   140.0   140.0   140.0     NaN
1  106   160.0   160.0   160.0   160.0   160.0   160.0     NaN
2  119   160.0   160.0   160.0   160.0   160.0   118.0     NaN
3  131   170.0   170.0   170.0   170.0   170.0   170.0     NaN
4  121     NaN     NaN     NaN     NaN     NaN     NaN     NaN
5  140     NaN     NaN     NaN     NaN     NaN     NaN     NaN
6  160     NaN     NaN     NaN     NaN     NaN     NaN     NaN
7  118     NaN     NaN     NaN     NaN     NaN     NaN     NaN
8  170     NaN     NaN     NaN     NaN     NaN     NaN     NaN

Python相关问答推荐

滚动和,句号来自Pandas列

ModuleNotFound错误:没有名为Crypto Windows 11、Python 3.11.6的模块

需要计算60,000个坐标之间的距离

运行总计基于多列pandas的分组和总和

matplotlib + python foor loop

关于两个表达式的区别

如果有2个或3个,则从pandas列中删除空格

mdates定位器在图表中显示不存在的时间间隔

Python日志(log)库如何有效地获取lineno和funcName?

在pandas中,如何在由两列加上一个值列组成的枢轴期间或之后可靠地设置多级列的索引顺序,

TypeError:';Locator';对象无法在PlayWriter中使用.first()调用

对数据帧进行分组,并按组间等概率抽样n行

如何在Quarto中的标题页之前创建序言页

如何在PYTHON中向单元测试S Side_Effect发送额外参数?

在MongoDB文档中仅返回数组字段

ValueError:必须在Pandas 中生成聚合值

如何将django url参数传递给模板&S url方法?

根据边界点的属性将图划分为子图

Fake pathlib.使用pyfakefs的类变量中的路径'

大Pandas 每月重新抽样200万只和300万只