gpt4 book ai didi

python-2.7 - 创建并使用内置 int 数据类型的 NumPy 数组

转载 作者:行者123 更新时间:2023-12-02 04:18:39 25 4
gpt4 key购买 nike

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

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: expected sequence items of type int, not numpy.int64

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

最佳答案

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

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'}

这些值以 24 字节 (6 * 4) 的形式存储,从数据内存位置开始。

a[0,0] 不仅仅是数据缓冲区中的 4 个字节。它实际上是一个单项 0d 数组。从技术上讲,它的类型是 np.int32,但它具有许多与 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) 测试。

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()。实际上它是:

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

关于python-2.7 - 创建并使用内置 int 数据类型的 NumPy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31905610/

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