使用内置int的dtype创建和使用NumPy数组 [英] create and use NumPy array with dtype of builtin int

查看:66
本文介绍了使用内置int的dtype创建和使用NumPy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从其他地方使用一种需要内置整数类型int而不是NumPy创建的类型的方法.这是一个简化:

I'm using a method from somewhere else which needs the built-in type of integers int and not the type NumPy creates. Here is a simplification:

a = np.arange(6, dtype='int').reshape(2,3)
b = a.tolist()

f(a[0,0]) # fails
f(b[0][0]) # works

失败给出错误消息:

TypeError:bpy_struct:item.attr = val:预期的序列项 输入int,而不是numpy.int64

TypeError: bpy_struct: item.attr = val: expected sequence items of type int, not numpy.int64

尽管tolist()可行,但我在此过程中松了NumPy.我的问题是,我可以使用内置类型的int来保持NumPy的形式和灵活性吗?

Although tolist() works, I loose NumPy in the process. My question is, can I maintain the NumPy form and flexibility, with the built-in type of int?

推荐答案

这可能有助于区分数组存储在其数据缓冲区中的内容以及通过索引返回的内容.

It may help to distinguish between what the array stores in its data buffer, and what it returns via indexing.

a=np.arange(6,dtype=int).reshape(2,3)

它的属性,a.__array_interface__

{'strides': None,
 'descr': [('', '<i4')],
 'shape': (2, 3),
 'data': (171366744, False),
 'version': 3,
 'typestr': '<i4'}

这些值从data内存位置开始存储24字节(6 * 4).

The values are stored a 24 bytes (6 * 4), starting at the data memory location.

a[0,0]不仅是数据缓冲区中的4个字节.它实际上是单个0d数组.从技术上讲,它的类型是np.int32,但是它具有与np.ndarray相同的属性和方法:

a[0,0] isn't just 4 bytes from the data buffer. It is really a single item 0d array. Technically its type is np.int32, but it has many of the same attributes and methods as an np.ndarray:

In [431]: a[0,0].__array_interface__
Out[431]: 
{'strides': None,
 'descr': [('', '<i4')],
 'shape': (),
 '__ref': array(0),
 'data': (171093512, False),
 'version': 3,
 'typestr': '<i4'}

.item()方法可用于将该值从数组对象中拉出.在许多情况下,int32可以像Python原语int一样使用,但是显然您的函数很挑剔,可以执行某种isinstance(i,int)测试.

.item() method can be used to pull that value out of the array object. In many cases an int32 can be used just like a Python primitive int, but evidently your function is picky, performing some sort of isinstance(i,int) test.

type(a[0,0])  # numpy.int32
type(a[0,0].item()) # int
type(int(a[0,0])  # int

a.tolist()[0][0]是因为该数组方法旨在构造Python原语的嵌套列表,其中删除了所有ndarray属性.实际上,它在最低级别执行.item().实际上是:

a.tolist()[0][0] because that array method is designed to construct a nested list of Python primitives, stripped of all ndarray attributes. In effect it does .item() at the lowest level. Effectively it is:

In [444]: [[j.item() for j in i] for i in a]
Out[444]: [[0, 1, 2], [3, 4, 5]]

这篇关于使用内置int的dtype创建和使用NumPy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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