gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:46:19 27 4
gpt4 key购买 nike

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

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

如果 a["x"] a["y"] 中的值设置为 "hello" 是否定的。据我所知,我应该这样做:

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

但这似乎改变了 a["x"] 中的值!我正在做的事情有什么问题,我还应该怎么做?

最佳答案

首先,在 numpy 结构化数组中,当您将数据类型指定为 str 时,numpy 假定它是一个 1 字符的字符串。

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

>>> print a.dtype
dtype([('x', '<i8'), ('y', 'S')])

因此,您输入的值被截断为 1 个字符。

>>> a["y"][0][0] = "hello"
>>> print a["y"][0][0]
h

因此使用数据类型作为 a10,其中 10 是字符串的最大长度。

引用this链接,它为其他数据结构指定了更多定义。

其次,您的方法对我来说似乎是正确的。

初始化数据类型为 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]]

关于python - NumPy - 根据结构化数组中的其他值设置结构化数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25219344/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com