python - 使用掩码和其他数组替换数组中的值

标签 python arrays pandas numpy indexing

我有一个一维“from”数组(称之为 frm),其中包含具有关联 bool 掩码数组的值: mask"(与 frm 形状相同)。然后我有第三个“替换”数组:repl,也是一维但长度比其他两个短。

有了这些,我想生成一个新数组 ("to"),其中包含 frm values except where mask==True 在这种情况下,它应该采用 in-order 来自 repl。 (请注意,maskTrue 元素的数量等于 repl 的长度).

我一直在寻找一种“聪明”的 numpy 方法来实现它?我查看了 np.wherenp.takenp.selectnp.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 类进行子类化,并且需要一个列/索引的“setter”。由于 pd.Index 不能被“切片索引”,我需要先复制索引/列数组,根据掩码替换副本中的一些元素,然后让 setter 设置完整的新值。让我知道是否有人知道更优雅的解决方案)。

最佳答案

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

关于python - 使用掩码和其他数组替换数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52123272/

相关文章:

Python:如何用一些已知的值初始化 OOP 列表?

python - 如何使用 kd-trees 确定字符串相似性?

arrays - 在 MATLAB 中用两个值替换向量值

python - 让垂直网格线出现在 matplotlib 的线图中

python - 如何在 Pandas 数据框中重新排序字符串并插入新字符串

python - 灯泡流 : difference between neo4jserver Graph and neo4jserver Neo4jclient

python - 增加 Python 中的内存限制?

javascript - Swig 模板 : How to check if value exists in array?

javascript - 如何在数组中分配测验答案的位置?

python - 查找每个业务季度 pandas 的最大列数