5

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?

4 Answers 4

3

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
Sign up to request clarification or add additional context in comments.

Comments

3
a = np.array([1,2,3])
b = np.empty(3, dtype='O')
b[:] = [a] * 3

should suffice.

Comments

0

I can't find any elegant solution, but at least a more general solution to doing everything by hand is to declare a function of the form:

def object_array(*args):
    array = np.empty(len(args), dtype=np.object)
    for i in range(len(args)):
        array[i] = args[i]
    return array

I can then do:

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

I then get:

>>> a = np.array([1,2,3])
>>> b = object_array(a,a,a)
>>> print b.dtype
object
>>> print b.shape
(3,)
>>> print b[0].dtype
int64

Comments

-1

I think anyarray is what you need here:

b = np.asanyarray([a,a,a])
>>> b[0].dtype
dtype('int32')

not sure what happened to the other 32bits of the ints though.

Not sure if it helps but if you add another array of a different shape, it converts back to the types you want:

import numpy as np
a = np.array([1,2,3])
b = np.array([1,2,3,4])
b = np.asarray([a,b,a], dtype=np.object)
print(b.dtype)
>>> object
print(b[0].dtype)
>>> int32

2 Comments

That must be my python running in 32bit.
That doesn't seem to work, as b.dtype is of type np.int64, not np.object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.