Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

python - Numpy object array of numerical arrays

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...