【问题标题】:Vectorized Python code for iterating and changing each column of a Pandas DataFrame within a window用于在窗口中迭代和更改 Pandas DataFrame 的每一列的矢量化 Python 代码
【发布时间】:2019-02-27 09:02:09
【问题描述】:

我有一个由 1 和 0 组成的数据框。我用循环遍历每一列。如果我在迭代中得到一个,我应该将它保留在列中。但是如果在这个之后的下一个n 位置有一些,我应该把它们变成零。然后重复相同的操作直到列的末尾,然后在每一列上重复所有这些操作。

是否有可能摆脱循环并使用 pandas/numpy 中的数据帧/矩阵/数组操作对所有内容进行矢量化?我应该怎么做? n 可以是 2 到 100 之间的任意值。

我尝试了这个功能,但失败了,如果它们之间至少有 n 零,它只会保留一个,这显然不是我需要的:

def clear_window(df, n):

    # create buffer of size n
    pad = pd.DataFrame(np.zeros([n, df.shape[1]]),
                       columns=df.columns)
    padded_df = pd.concat([pad, df])

    # compute rolling sum and cut off the buffer
    roll = (padded_df
            .rolling(n+1)
            .sum()
            .iloc[n:, :]
           )

    # delete ones where rolling sum is above 1 or below -1
    result = df * ((roll == 1.0) | (roll == -1.0)).astype(int)

    return result

【问题讨论】:

  • 您能否退后一步,将任务视为您对整个专栏所做的事情,而不是关注顺序问题?这就是“矢量化”的意思。

标签: python pandas numpy dataframe vectorization


【解决方案1】:

如果您找不到向量化的方法,Numba 将帮助您加快处理这些顺序循环问题的速度。

此代码循环遍历每一行以查找目标值。当目标值 (1) 找到后,将接下来的 n 行设置为填充值 (0)。搜索行索引 递增以跳过填充行并开始下一次搜索。

from numba import jit

@jit(nopython=True)
def find_and_fill(arr, span, tgt_val=1, fill_val=0):
    start_idx = 0
    end_idx = arr.size
    while start_idx < end_idx:
        if arr[start_idx] == tgt_val:
            arr[start_idx + 1 : start_idx + 1 + span] = fill_val
            start_idx = start_idx + 1 + span
        else:
            start_idx = start_idx + 1
    return arr

df2 = df.copy()
# get the dataframe values into a numpy array
a = df2.values

# transpose and run the function for each column of the dataframe
for col in a.T:
    # fill span is set to 6 in this example
    col = find_and_fill(col, 6)

# assign the array back to the dataframe
df2[list(df2.columns)] = a

# df2 now contains the result values

【讨论】:

    猜你喜欢
    • 2021-02-07
    • 2019-09-25
    • 2018-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-13
    • 2020-05-21
    • 1970-01-01
    相关资源
    最近更新 更多