为什么单个Numpy数组元素不是Python标量? [英] Why a single Numpy array element is not a Python scalar?

查看:93
本文介绍了为什么单个Numpy数组元素不是Python标量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释Numpy设计的决定,即保持数组的单个元素与Python标量不同吗?

Can someone explain the Numpy design decision to keep single elements of arrays as distinct from Python scalars?

以下代码可以正常运行

import numpy as np
a = np.array([1, 2, 3])
b = a[0]
print(b.size)

这说明b不是一个简单的Python标量,实际上type(b)给出了numpy.int32而不是int.

This illustrates that b is not a simple Python scalar, and in fact type(b) gives numpy.int32 instead of int.

当然,如果定义了b = 1,则命令b.size会引发错误,因为

Of course, if one defines b = 1, the command b.size throws an error because

AttributeError:"int"对象没有属性"size"

AttributeError: 'int' object has no attribute 'size'

我发现这种行为上的差异令人困惑,我想知道它的动机是什么.

I find this difference of behaviour confusing and I am wondering what is its motivation.

推荐答案

对数组中的元素和建立索引的对象之间存在差异.

There is a difference between elements of an array and the object you get when indexing one.

该数组有一个数据缓冲区.它是numpy用自己的编译代码管理的一个字节块.各个元素可以用1字节,4、8、16等表示.

The array has a data buffer. It is a block of bytes the numpy manages with its own compiled code. Individual elements may be represented by 1 byte, 4, 8, 16, etc.

In [478]: A=np.array([1,2,3])

In [479]: A.__array_interface__
Out[479]: 
{'data': (167487856, False),
 'descr': [('', '<i4')],
 'shape': (3,),
 'strides': None,
 'typestr': '<i4',
 'version': 3}

以字节列表(显示为字符)查看数据:

view the data as a list of bytes (displayed as characters):

In [480]: A.view('S1')
Out[480]: 
array(['\x01', '', '', '', '\x02', '', '', '', '\x03', '', '', ''], 
      dtype='|S1')

选择A的元素时,您将返回一个元素数组(或类似的元素):

When you select an element of A you get back a one element array (or something like it):

In [491]: b=A[0]

In [492]: b.shape
Out[492]: ()

In [493]: b.__array_interface__
Out[493]: 
{'__ref': array(1),
 'data': (167480104, False),
 'descr': [('', '<i4')],
 'shape': (),
 'strides': None,
 'typestr': '<i4',
 'version': 3}

type不同,但是bAshapestridesmean等具有大多数相同的属性.

The type is different, but b has most of the same attributes as A, shape, strides, mean, etc.

您必须使用.item来访问基础的标量":

You have to use .item to access the underlying 'scalar':

In [496]: b.item()
Out[496]: 1

In [497]: type(b.item())
Out[497]: int

因此,您可以将b视为带有numpy包装器的标量. b__array_interface__看起来很像np.array(1)的.

So you can think of b as a scalar with a numpy wrapper. The __array_interface__ for b looks very much like that of np.array(1).

这篇关于为什么单个Numpy数组元素不是Python标量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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