You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

寻求NumPy/Pandas实现数组双任务的高效非迭代方案

数组处理优化需求

现有两个数组:

arr1 = [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0]
arr2 = [0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0]

需完成的两项任务

  1. 对比两数组,若同一位置均为1,则找出每个数组中该位置向前最近的0,将对应数组的该位置1替换为0;
  2. 将数组中后续紧跟1的所有1替换为0。

已实现的迭代代码

本人已通过迭代代码实现上述功能,代码如下:

任务1迭代代码

df = pd.DataFrame({"A": arr1, "B": arr2, })
df2 = df[(df.A > 0) & (df.B > 0)]
i = 1
for idx in df2.index:
    while df.loc[idx, 'A'] == 1 and df.loc[idx, 'B'] == 1:
        try:
            if df.loc[idx - i, 'A'] > 0 or df.loc[idx - i, 'B'] > 0:
                df.loc[idx, 'A'] = df.loc[idx - i, 'A']
                df.loc[idx, 'B'] = df.loc[idx - i, 'B']
            else:
                i += 1
        except KeyError:
            df.loc[idx, 'A'] = 0
            df.loc[idx, 'B'] = 0

任务2迭代代码

df2 = df[(df.A > 0)].A
for idx in df2.index:
    if df.loc[idx + 1, 'A'] > 0:
        df.loc[idx, 'A'] = 0
df2 = df[(df.B > 0)].B
for idx in df2.index:
    if df.loc[idx + 1, 'B'] > 0:
        df.loc[idx, 'B'] = 0

优化需求

希望找到NumPy或Pandas的高效、简洁(如一行式)解决方案。

内容的提问来源于stack exchange,提问作者Viktor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 11:49:52