NumPy - 根据结构数组中的其他值设置结构数组中的值

7 投票
1 回答
2324 浏览
提问于 2025-04-18 16:40

我有一个结构化的NumPy数组:

a = numpy.zeros((10, 10), dtype=[
    ("x", int),
    ("y", str)])

我想把a["y"]中的值设置为"hello",前提是a["x"]中对应的值是负数。根据我的理解,我应该这样做:

a["y"][a["x"] < 0] = "hello"

但是这样似乎会改变a["x"]中的值!我这样做有什么问题,应该怎么做才好呢?

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]]

撰写回答