NumPy-根据结构化数组中的其他值设置结构化数组中的值 [英] NumPy - Set values in structured array based on other values in structured array
问题描述
我有一个结构化的NumPy数组:
I have a structured NumPy array:
a = numpy.zeros((10, 10), dtype=[
("x", int),
("y", str)])
如果a["x"]
中的相应值为负,我想将a["y"]
中的值设置为"hello"
.据我所知,我应该这样做:
I want to set values in a["y"]
to either "hello"
if the corresponding value in a["x"]
is negative. As far as I can tell, I should be doing that like this:
a["y"][a["x"] < 0] = "hello"
但是这似乎改变了a["x"]
中的值!我在做什么,怎么办?我还应该怎么做?
But this seems to change the values in a["x"]
! What is the problem with what I'm doing, and how else should I do this?
推荐答案
首先,在numpy结构化数组中,当您将数据类型指定为str
时,numpy
假定其为1个字符串.
First of all, in numpy structured arrays, when you specify datatype as str
numpy
assumes it to be a 1 character string.
>>> a = numpy.zeros((10, 10), dtype=[
("x", int),
("y", str)])
>>> print a.dtype
dtype([('x', '<i8'), ('y', 'S')])
结果,您输入的值将被截断为1个字符.
As a result the values you enter get truncated to 1 character.
>>> a["y"][0][0] = "hello"
>>> print a["y"][0][0]
h
因此将数据类型用作a10
,其中10是字符串的最大长度.
Hence use data type as a10
, Where 10 being the max length of your string.
引用此链接,它为其他数据结构指定了更多定义.
Refer this link, which specifies more definitions for other data structures.
第二,您的方法对我来说似乎是正确的.
Secondly your approach seems correct to me.
启动数据类型为int和a10
Inititating a structured numpy array with datatype int and a10
>>> a = numpy.zeros((10, 10), dtype=[("x", int), ("y", 'a10')])
用随机数填充
>>> a["x"][:] = numpy.random.randint(-10, 10, (10,10))
>>> print a["x"]
[[ 2 -4 -10 -3 -4 4 3 -8 -10 2]
[ 5 -9 -4 -1 9 -10 3 0 -8 2]
[ 5 -4 -10 -10 -1 -8 -1 0 8 -4]
[ -7 -3 -2 4 6 6 -8 3 -8 8]
[ 1 2 2 -6 2 -9 3 6 6 -6]
[ -6 2 -8 -8 4 5 8 7 -5 -3]
[ -5 -1 -1 9 5 -7 2 -2 -9 3]
[ 3 -10 7 -8 -4 -2 -4 8 5 0]
[ 5 6 5 8 -8 5 -10 -6 -2 1]
[ 9 4 -8 6 2 4 -10 -1 9 -6]]
应用过滤器
>>> a["y"][a["x"]<0] = "hello"
>>> print a["y"]
[['' 'hello' 'hello' 'hello' 'hello' '' '' 'hello' 'hello' '']
['' 'hello' 'hello' 'hello' '' 'hello' '' '' 'hello' '']
['' 'hello' 'hello' 'hello' 'hello' 'hello' 'hello' '' '' 'hello']
['hello' 'hello' 'hello' '' '' '' 'hello' '' 'hello' '']
['' '' '' 'hello' '' 'hello' '' '' '' 'hello']
['hello' '' 'hello' 'hello' '' '' '' '' 'hello' 'hello']
['hello' 'hello' 'hello' '' '' 'hello' '' 'hello' 'hello' '']
['' 'hello' '' 'hello' 'hello' 'hello' 'hello' '' '' '']
['' '' '' '' 'hello' '' 'hello' 'hello' 'hello' '']
['' '' 'hello' '' '' '' 'hello' 'hello' '' 'hello']]
验证a["x"]
>>> print a["x"]
[[ 2 -4 -10 -3 -4 4 3 -8 -10 2]
[ 5 -9 -4 -1 9 -10 3 0 -8 2]
[ 5 -4 -10 -10 -1 -8 -1 0 8 -4]
[ -7 -3 -2 4 6 6 -8 3 -8 8]
[ 1 2 2 -6 2 -9 3 6 6 -6]
[ -6 2 -8 -8 4 5 8 7 -5 -3]
[ -5 -1 -1 9 5 -7 2 -2 -9 3]
[ 3 -10 7 -8 -4 -2 -4 8 5 0]
[ 5 6 5 8 -8 5 -10 -6 -2 1]
[ 9 4 -8 6 2 4 -10 -1 9 -6]]
这篇关于NumPy-根据结构化数组中的其他值设置结构化数组中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!