python - 使用掩码替换numpy中的字符串

标签 python numpy mask

如果我有一个看起来像 ar 的数组,它是一个 numpy 数组?如何使用 numpy mask 将所有“replaceme”替换为 2012。

ar = [['replaceme', 1,2], ['replaceme', 3,4],['replaceme', 5,6]]

ar = [[2012, 1,2], [2012, 3,4],[2012, 5,6]]

最佳答案

这不是面具的工作advanced indexing :

>>> import numpy as np
>>> ar = np.array([['replaceme', 1,2], ['replaceme', 3,4],['replaceme', 5,6]], dtype=object)
>>> ar
array([[replaceme, 1, 2],
       [replaceme, 3, 4],
       [replaceme, 5, 6]], dtype=object)
>>> ar == "replaceme"
array([[ True, False, False],
       [ True, False, False],
       [ True, False, False]], dtype=bool)

所以我们需要做的就是:

>>> ar[ar == "replaceme"] = 2012
>>> ar
array([[2012, 1, 2],
       [2012, 3, 4],
       [2012, 5, 6]], dtype=object)

关于python - 使用掩码替换numpy中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14095752/

相关文章:

python - Pygame快速像素读取

python - 将numpy数组转换为结构化数组

python - 属性错误: module 'urwid' has no attribute 'Text'

performance - 如何有效地获取 10% 的随机数,然后获取剩余 90 个随机数的 10% 等,直到所有点都分配完毕

python - 如何提高时间序列重合过滤的性能?

html - 使用 CSS 在父元素中切一个洞

ios - 使用 CAShapeLayer 屏蔽呈现 View Controller 也屏蔽呈现 View Controller

python - 如何解决 "ModuleNotFoundError: No module named ' PIL'"的问题?

python - Pandas 四舍五入小数不起作用

canvas - 如何使用 flutter 的自定义绘制使用 png UI 图像屏蔽小部件