NumPy - 根据结构数组中的其他值设置结构数组中的值
1 个回答
6
首先,在numpy的结构化数组中,当你把数据类型指定为 str
时,numpy
会认为这只是一个字符的字符串。
>>> a = numpy.zeros((10, 10), dtype=[
("x", int),
("y", str)])
>>> print a.dtype
dtype([('x', '<i8'), ('y', 'S')])
因此,你输入的值会被截断,只保留一个字符。
>>> a["y"][0][0] = "hello"
>>> print a["y"][0][0]
h
所以,建议使用数据类型 a10
,这里的10是你字符串的最大长度。
可以参考这个链接,里面有更多关于其他数据结构的定义。
其次,我觉得你的做法是正确的。
你可以用数据类型为int和 a10
来初始化一个结构化的numpy数组。
>>> 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]]