【问题标题】:Replace values in array using mask and other array使用掩码和其他数组替换数组中的值
【发布时间】:2019-02-06 22:44:55
【问题描述】:

我有一个一维“来自”数组(称为 "frm"),其中包含带有相关布尔掩码数组的值:"面具"(与frm的形状相同)。然后我有第三个“替换”数组:"repl",也是 1D,但长度比其他两个短。

有了这些,我想生成一个包含 frm 的新数组 ("to") > values except where mask==True 在这种情况下,它应该按顺序从 repl em>。 (注意 mask 中 True 元素的数量等于 repl 的长度)。

我正在寻找一种“聪明”的 numpy 方式来实现这一点?我查看了 np.where、np.take、np.select、np.choose 等方法,但没有似乎“符合要求”?

“切入代码”,这就是我目前所拥有的。它工作正常,但似乎不是“Numpythonic”? (或者甚至是 Pythonic)

frm  = [1, 2, 3, 4, 5]
mask = [False, True, False, True, True]
repl = [200, 400, 500]
i = 0; to = []
for f,m in zip(frm,mask):
    if m:
        to.append(repl[i])
        i += 1
    else:
        to.append(f)
print(to)

产量:[1, 200, 3, 400, 500]

(背景:我需要这样做的原因是因为我是 Pandas pd.Dataframe 类的子类,并且需要列/索引的“设置器”。由于 pd.Index 不能“切片索引”,我需要先复制索引/列数组,根据掩码替换副本中的一些元素,然后使用 setter em> 设置完整的新值。如果有人知道更优雅的解决方案,请告诉我)。

【问题讨论】:

    标签: python arrays pandas numpy indexing


    【解决方案1】:

    numpy解决方案:

    这很简单:

    # convert frm to a numpy array:
    frm = np.array(frm)
    # create a copy of frm so you don't modify original array:
    to = frm.copy()
    
    # mask to, and insert your replacement values:
    to[mask] = repl
    

    然后to 返回:

    >>> to
    array([  1, 200,   3, 400, 500])
    

    pandas解决方案:

    如果您的数据框看起来像:

    >>> df
       column
    0       1
    1       2
    2       3
    3       4
    4       5
    

    那么你可以使用loc:

    df.loc[mask,'column'] = repl
    

    然后你的数据框看起来像:

    >>> df
       column
    0       1
    1     200
    2       3
    3     400
    4     500
    

    【讨论】:

    • 重新 numpy 解决方案:很好!在这里,我正在寻找“特殊方法”,完全忽略了我可以使用索引掩码简单地分配给变量的事实! :-)
    • 重新使用 Pandas 解决方案:我知道将 "loc" 用于 DataFrame 的 contents。据我所知,轴没有等价物(“索引”和“列”名称,而不是数据框 inside 的实际值)。例如:df.columns[3] 有效。但是df.columns[3] = "new-name" 给出了TypeError: "Index does not support mutable operations"(这促使我将它纳入 numpy 的解决方案)。
    • 哦,我想我误解了你的目的......是的,最好在 numpy 中执行此操作并将结果数组用作索引 (IIUC)
    猜你喜欢
    • 1970-01-01
    • 2015-11-03
    • 2013-07-30
    • 2015-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    • 2021-05-22
    相关资源
    最近更新 更多