更新 numpy.ndarray 中的值 [英] Updating a value in numpy.ndarray

查看:127
本文介绍了更新 numpy.ndarray 中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更新数组中的元素.如果我有一个数组说:

I'm trying to to update an element in an array. If I've got an array say:

[[0, 0],
 [0, 0]]

据我所知更新方式,例如.到 0.5 的第一个元素是

as far as I knew the way to update eg. the first element to 0.5, was

array[0,0] = 0.5

然而,当我打印数组时,内容没有改变.我在 Stack Overflow 上阅读了一些关于创建数组副本的内容,但我不知道这是否适用.

However when I print the array the contents are unchanged. I read some things on Stack Overflow about copies being created of arrays but I don't know if this applies.

任何帮助都会很棒

推荐答案

你的问题是你的数组是整数值(因为你用整数初始化它),当你向它写入一个浮点数时,它被四舍五入为 0. 你可以检查一下,如果你写

Your problem is that your array is integer-valued (because you initialize it with integers), and when you write a float to it, it gets rounded to 0. You can check that this is the case if you write

array = np.array([[0, 0], [0, 0]])
array[0, 0] = 1.5
>>> array = array([[1, 0],
                   [0, 0]])

要获得预期的行为,请使用浮点数对其进行初始化

To get the expected behaviour, either initialize it with floats

array = np.array([[0., 0.], [0., 0.]])

或明确指定dtype

array = np.array([[0, 0], [0, 0]], dtype=np.float32)

这篇关于更新 numpy.ndarray 中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆