[英]Working with NumPy structured arrays
I am working with a NumPy structured array with the following structure: 我正在使用具有以下结构的NumPy结构化数组:
ar = np.array([(760., 0), (760.3, 0), (760.5, 0), (280.0, 1), (320.0, 1), (290.0, 1)], dtype=[('foo', 'f4'),('bar', 'i4')])
What is an efficient way of extracting the 'foo' fields for a specific value of 'bar'? 提取特定值“ bar”的“ foo”字段的有效方法是什么? For example, I would like to store all the 'foo' values for which 'bar' is 0 in an array:
例如,我想将'bar'为0的所有'foo'值存储在数组中:
fooAr = ar['foo'] if ar['bar'] is 0
The above does not work. 上面的方法不起作用。
Use ar['foo'][ar['bar'] == 0]
: 使用
ar['foo'][ar['bar'] == 0]
:
ar = np.array([(760., 0), (760.3, 0), (760.5, 0), (280.0, 1), (320.0, 1), (290.0, 1)], dtype=[('foo', 'f4'),('bar', 'i4')])
print(ar['bar'] == 0)
# array([ True, True, True, False, False, False], dtype=bool)
result = ar['foo'][ar['bar'] == 0]
print(result)
# array([ 760. , 760.29998779, 760.5 ], dtype=float32)
Note that since a boolean selection mask, ar['bar'] == 0
, is used, result
is a copy of parts of ar['foo']
. 注意,由于使用了布尔选择掩码
ar['bar'] == 0
, result
是ar['foo']
部分的副本 。 Thus, modifying result
would not affect ar
itself. 因此,修改
result
不会影响ar
本身。
To modify ar
assign to ar['foo'][mask]
directly: 要修改
ar
将其分配给ar['foo'][mask]
:
mask = (ar['bar'] == 0)
ar['foo'][mask] = 100
print(ar)
# array([(100.0, 0), (100.0, 0), (100.0, 0), (280.0, 1), (320.0, 1), (290.0, 1)],
# dtype=[('foo', '<f4'), ('bar', '<i4')])
Assignment to ar['foo'][mask]
calls ar['foo'].__setitem__
which affects ar['foo']
. 分配给
ar['foo'][mask]
调用ar['foo'].__setitem__
,这会影响ar['foo']
。 Since ar['foo']
is a view of ar
, modifying ar['foo']
affects ar
. 由于
ar['foo']
是ar
的视图 ,因此修改ar['foo']
会影响ar
。
Note that the order of indexing matters here. 请注意,这里的索引顺序很重要 。 If you tried applying the boolean mask before selecting the
'foo'
field, as in: 如果您在选择
'foo'
字段之前尝试应用布尔掩码,则如下所示:
ar[mask]['foo'] = 99
Then this would not affect ar
, since ar[mask]
is a copy of ar
. 那么这不会影响
ar
,因为ar[mask]
是ar
的副本 。 Nothing done to the copy ( ar[mask]
) affects the original ( ar
). 对副本(
ar[mask]
)所做的任何操作均不会影响原件( ar
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.