有没有更好的方法将新值分配给numpy数组标量

有没有更好的方法将新值分配给numpy数组标量

本文介绍了有没有更好的方法将新值分配给numpy数组标量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在对numpy数组中的标量值进行一些快速计算.正如文档

I am doing some quick calculations on a scalar value from a numpy array. As it says in the documentation,

但是,有比这更好(更快,更简洁)的方式将新值分配给现有数组标量了:

But is there a better (faster, and more concise) way of assigning a new value to an existing array scalar than this:

>>> x = np.array(2.0, dtype='float32')

可以,但是不太方便(我正在做其他算术,并且希望保留整个类型).

which works but is not that convenient (I am doing other arithmetic and want to preserve the type throughout).

由于明显的原因,此方法不起作用:

This doesn't work for obvious reasons:

>>> x = np.array(1.0, dtype='float32')
>>> print(x, type(x))
1.0 <class 'numpy.ndarray'>
>>> x = 2.0
>>> print(x, type(x))
2.0 <class 'float'>

这也不是:

>>> x = np.array(1.0, dtype='float32')
>>> x[] = 2.0
  File "<ipython-input-319-7f36071ff81d>", line 2
    x[] = 2.0
      ^
SyntaxError: invalid syntax

也不是:

>>> x = np.array(1.0, dtype='float32')
>>> x[:] = 2.0
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-24-62cd4ca238ce> in <module>()
      1 x = np.array(1.0, dtype='float32')
----> 2 x[:] = 2.0

IndexError: too many indices for array

更新:

基于下面的评论(谢谢),我现在意识到我实际上并没有使用数组标量. x是零维数组.

Based on comments below (thanks) I have now realised that I am not actually using array scalars. x is a zero-dimensional array.

以下是创建数组标量的方法:

Here is how to create an array scalar:

>>> a = np.array((1.0, 2.0, 3.0), dtype='float32')
>>> x = a[0]
>>> print(x, type(x))
1.0 <class 'numpy.float32'>

或者简单地:

>>> x = np.float32(1.0)
>>> print(x, type(x))
1.0 <class 'numpy.float32'>

推荐答案

可以修改0d数组,但array scalar不能:

A 0d array can be modified, but an array scalar cannot:

In [199]: x = np.array(1.0, 'float32')
In [200]: x
Out[200]: array(1., dtype=float32)
In [201]: x.shape
Out[201]: ()
In [202]: x[...] = 2
In [203]: x
Out[203]: array(2., dtype=float32)
In [204]: x[()] =3
In [205]: x
Out[205]: array(3., dtype=float32)

您必须对x进行突变,而不是将新对象分配给该变量.

You have to mutate x, not assign a new object to the variable.

也就是说,我不明白为什么有人想要或需要这样做.

That said, I don't see why one would want, or need, to do this.

此0d数组与array scalar不太相同:

This 0d array is not quite the same as an array scalar:

In [207]: y = np.float32(1)
In [208]: y[...] = 2
....
TypeError: 'numpy.float32' object does not support item assignment

使用索引从数组中提取元素会产生array scalar:

Extracting an element from an array with indexing produces an array scalar:

In [210]: type(x[()])
Out[210]: numpy.float32

float32对象具有许多数组属性,甚至包括方法,但并不完全相同:

The float32 object has many of the array attributes, even methods, but it isn't quite same:

In [211]: x.shape
Out[211]: ()
In [212]: y.shape
Out[212]: ()


可以使用与数组形状相同大小的元组对数组进行索引. arr[1,2]arr[(1,2)]相同. x的形状为(),因此只能使用空元组x[()]对其进行索引.类似地,arr[:,:]适用于2d数组,但不适用于1d. ...表示任意数量的切片,因此可与x[...]一起使用.


An array can be indexed with a tuple the same size as its shape. arr[1,2] is the same as arr[(1,2)]. The shape of x is (), so it can only be indexed with an empty tuple, x[()]. Similarly arr[:,:] works for a 2d array, but not for 1d. ... means, any number of slices, so works with x[...].

已经为np.generic类对象定义了足够的__getitem__,以允许像[...][()]这样的索引.但是尚未定义分配.

Enough of the __getitem__ has been defined for np.generic class objects to allow indexing like [...] and [()]. But the assignment has not been defined.

查看诸如np.ndarraynp.int_np.float32np.floatnp.int之类的类的类层次结构可能会很有用.

It might be useful to look at the class hierarchy of classes like np.ndarray, np.int_, np.float32, np.float, and np.int.

从您的链接中: https ://docs.scipy.org/doc/numpy-1.13.0/user/basics.types.html#array-scalars

使用数组标量的主要优点是它们保留了数组类型(Python可能没有可用的匹配标量类型,例如int16).因此,使用数组标量可确保数组和标量之间的行为相同,而不管该值是否在数组内部. NumPy标量也具有许多与数组相同的方法.

The primary advantage of using array scalars is that they preserve the array type (Python may not have a matching scalar type available, e.g. int16). Therefore, the use of array scalars ensures identical behaviour between arrays and scalars, irrespective of whether the value is inside an array or not. NumPy scalars also have many of the same methods arrays do.

第二段写在第一段的上下文中.它试图解释为什么数组的元素是returned as array scalars.这就是为什么arr[0,1]返回np.float32对象而不是Python float的原因.

The 2nd paragraph is written the context of the 1st. It attempts to explain why elements of an array are returned as array scalars. That is, why arr[0,1] returns a np.float32 object, as opposed to a Python float.

这并不意味着我们直接创建array scalar.

It is not suggesting that we create an array scalar directly.

我首先写了这个答案,以掩盖0d数组与该引用所称的array scalars之间的区别.

I first wrote this answer glossing over the difference between a 0d array, and what this quote is calling array scalars.

这篇关于有没有更好的方法将新值分配给numpy数组标量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 18:01