Python 在选定的行上应用程序

Python 在选定的行上应用程序,python,pandas,Python,Pandas,如何仅对选定行应用pandas滚动+应用 df = pd.DataFrame({'A':range(10)}) # We want the rolling mean values at rows [4,8] rows_to_select = [4,8] # We can calculate rolling values of all rows first, then do the selections roll_mean = df.A.rolling(3).mean() result = r

如何仅对选定行应用pandas
滚动
+
应用

df = pd.DataFrame({'A':range(10)})

# We want the rolling mean values at rows [4,8]
rows_to_select = [4,8]

# We can calculate rolling values of all rows first, then do the selections
roll_mean = df.A.rolling(3).mean()
result = roll_mean[rows_to_select]

但在处理非常大的数据集时,这不是一个选项,只需要滚动值的子集。是否可以执行某种类型的
滚动
+
选择
+
应用

我觉得您可以使用for循环,正如您所提到的,当数据帧很大时,如果我们只需要几个值,那么针对整个数据帧运行对我们没有好处,特别是您需要滚动,这被认为是内存成本函数

n=3
l=[df.loc[x-n+1:x].mean()[0]for x in rows_to_select]
l
[3.0, 7.0]
使用滑动窗口视图 我们可以在输入序列中创建滑动窗口作为视图,为自己创建一个
2D
数组,然后简单地用所选行对其进行索引,并沿该
2D
数组的第二个轴计算平均值。这就是所需的输出,并且都是以矢量化的方式进行的

为了得到那些滑动窗口,有一个简单的内置。我们将利用它

执行工作将是:-

from skimage.util.shape import view_as_windows

W = 3 # window length

# Get sliding windows
w = view_as_windows(df['A'].to_numpy(copy=False),W)

# Get selected rows of slding windows. Get mean value.
out_ar = w[np.asarray(rows_to_select)-W+1].mean(1)

# Output as series if we need in that format
out_s = pd.Series(out_ar,index=df.index[rows_to_select])
In [91]: rolling_selected_rows(df['A'], rows_to_select, W=3, func=np.min)
Out[91]: 
4    2
8    6
dtype: int64
要想将其保持在NumPy范围内,可以选择
将其视为windows
-


扩展到所有还原操作

所有支持缩减操作的NumPy UFUNC都可以扩展以使用此方法,如下所示-

def rolling_selected_rows(s, rows, W, func):
    # Get sliding windows
    w = view_as_windows(s.to_numpy(copy=False),W)
    
    # Get selected rows of slding windows. Get mean value.
    out_ar = func(w[np.asarray(rows)-W+1],axis=1)
    
    # Output as series if we need in that format
    out_s = pd.Series(out_ar,index=s.index[rows])
    return out_s
因此,要为给定样本的选定行获取滚动
min
值,需要-

from skimage.util.shape import view_as_windows

W = 3 # window length

# Get sliding windows
w = view_as_windows(df['A'].to_numpy(copy=False),W)

# Get selected rows of slding windows. Get mean value.
out_ar = w[np.asarray(rows_to_select)-W+1].mean(1)

# Output as series if we need in that format
out_s = pd.Series(out_ar,index=df.index[rows_to_select])
In [91]: rolling_selected_rows(df['A'], rows_to_select, W=3, func=np.min)
Out[91]: 
4    2
8    6
dtype: int64

给我们看一些数据?只是为了更清楚地说明你想要什么。不管怎样,
apply
AFAIK都会在引擎盖下循环。所以,不要认为这比显式循环更好。