数值数组的 Numpy 对象数组 [英] Numpy object array of numerical arrays

查看:38
本文介绍了数值数组的 Numpy 对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 dtype=np.object 创建一个数组,其中每个元素都是一个数字类型的数组,例如 int 或 float.例如:

<预><代码>>>>a = np.array([1,2,3])>>>b = np.empty(3,dtype=np.object)>>>b[0] = a>>>b[1] = a>>>b[2] = a

创造我想要的:

<预><代码>>>>打印 b.dtype目的>>>打印 b.shape(3,)>>>打印 b[0].dtypeint64

但我想知道是否没有办法在一行中写入第 3 到 6 行(特别是因为我可能想要连接 100 个数组).我试过了

<预><代码>>>>b = np.array([a,a,a],dtype=np.object)

但这实际上将所有元素转换为 np.object:

<预><代码>>>>打印 b.dtype目的>>>打印 b.shape(3,)>>>打印 b[0].dtype目的

有人知道如何避免这种情况吗?

解决方案

它不是很漂亮,但是...

将 numpy 导入为 npa = np.array([1,2,3])b = np.array([None, a, a, a])[1:]打印 b.dtype, b[0].dtype, b[1].dtype# 对象 int32 int32

I want to create an array with dtype=np.object, where each element is an array with a numerical type, e.g int or float. For example:

>>> a = np.array([1,2,3])
>>> b = np.empty(3,dtype=np.object)
>>> b[0] = a
>>> b[1] = a
>>> b[2] = a

Creates what I want:

>>> print b.dtype
object

>>> print b.shape
(3,)

>>> print b[0].dtype
int64

but I am wondering whether there isn't a way to write lines 3 to 6 in one line (especially since I might want to concatenate 100 arrays). I tried

>>> b = np.array([a,a,a],dtype=np.object)

but this actually converts all the elements to np.object:

>>> print b.dtype
object

>>> print b.shape
(3,)

>>> print b[0].dtype
object

Does anyone have any ideas how to avoid this?

解决方案

It's not exactly pretty, but...

import numpy as np

a = np.array([1,2,3])
b = np.array([None, a, a, a])[1:]

print b.dtype, b[0].dtype, b[1].dtype
# object int32 int32

这篇关于数值数组的 Numpy 对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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