python - 就地修改 NumPy recarray 的高级索引子集

标签 python arrays indexing numpy

我有一个 recarray,其中包含几个用于选择子集的列。有点像

>>> x
   array([ ('label1',True,3),
          ('label2',True,2),
          ('label1',False,4)],
         dtype=[('status', '|S16'), ('select', '|b1'), ('somedata', '<i4')])

使用类似于 previous SO question 的方法从此数组中选择数据.

condit=(x['status']=='label1')&(x['select']==True)
x_subids=numpy.where(condit)[0]
x_sub=x[x_subids]

然后我在子集上做一些工作并更新原始的。

x[x_subids]=x_sub

我知道 x_sub 是一个副本而不是一个 View ,因为高级索引,我想知道是否有一种优雅的方法来避免数组复制并只在给定条件的情况下使用原始文件我需要对数据进行子集化。

最佳答案

您在我的第一个答案的评论中提到的那种修改可以用 numpy.place() function 完成:

>>> import numpy
>>> x = numpy.array([("label1",True,3), ("label2",False,2), ("label1",True,4)],
...     dtype=[("status", "|S16"), ("select", "|b1"), ("somedata", ">> mask = x["select"]
>>> numpy.place(x["somedata"], mask, (5, 6))
>>> print x
[('label1', True, 5) ('label2', False, 2) ('label1', True, 6)]
>>> numpy.place(x["status"], mask, "label3")
>>> print x
[('label3', True, 5) ('label2', False, 2) ('label3', True, 6)]

注意

  1. 为了相关示例,我稍微更改了值和条件。

  2. 这一次,再次选择 maskTrue 的值,而不是像我之前的回答那样被屏蔽掉。

  3. 掩码 condit 中的 ==True 部分是多余的,只需将其删除 :)

关于python - 就地修改 NumPy recarray 的高级索引子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4111514/

相关文章:

python - 用python从二进制文件中读取32位带符号的ieee 754 float ?

python - 等式比较在 TensorFlow 2.0 tf.function() 中不起作用

c - 指针数组的基础

python Pandas : How can I group by and assign an id to all the items in a group?

arrays - Swift 数组不返回所有值

python - optparse 描述中的 ASCII 艺术

python - 如何防止并行 python 以 "OSError: [Errno 35] Resource temporarily unavailable"退出?

c - 在C中的数组中强制范围

c++ - 使用指向我的数组的指针在 C++ 中给我一个 "Unhandled exception"?

r - R : Error when grouping data using subset or index methods- produces list of all column names