Douglas Camata
Douglas Camata

Reputation: 597

Transform array of array into NumPy's ndarray of ndarrays

I've been trying to transform an array of arrays with a numpy ndarray of ndarrays.

This is my dtype:

dt = 'i8,i8,i8,i8,i8,i8,i8,i8,i8,i8,i8,i8,i8,f8,i8,i8,f8,f8,f8,a50,a50,a50,a50'

And this is my data:

# data array reduced to one row for sake of readability
data = [[45608L, 0L, 46115L, 11952L, 11952L, 0, 0, 0, 0, 0, 11951L, 11951L, 46176L, 9.0, 0, 1, 1407340577.0, 1407340577.0, 0, 'Simulation Movement', 'planned', '', ''],]

I already tried these ways:

np.array(data, dt)
np.array([np.array(row, dt) for row in data])

But when I run both these I get:

TypeError: expected a readable buffer object

Buuuuut, if I call np.array with an array only containing each single element of my rows and using the appropriate data type (did this using a loop with enumerate and a split dt) , it works. Was something like this:

for row in data:
  for index, value in enumerate(row):
    np.array([value,], dt.split(',')[index])

Any ideas, please?

Upvotes: 2

Views: 186

Answers (1)

Anand S Kumar
Anand S Kumar

Reputation: 91009

Seems like for this to work, you would need to convert the inner list into tuple. Example -

import numpy as np

dt = 'i8,i8,i8,i8,i8,i8,i8,i8,i8,i8,i8,i8,i8,f8,i8,i8,f8,f8,f8,a50,a50,a50,a50'

data = [[45608L, 0L, 46115L, 11952L, 11952L, 0, 0, 0, 0, 0, 11951L, 11951L, 46176L, 9.0, 0, 1, 1407340577.0, 1407340577.0, 0, 'Simulation Movement', 'planned', '', ''],]

result = np.array(map(tuple, data),dt)

Demo run here. But with this you get an array of 1 element back shape = (1,) (the 1 element being the tuple).


You can also use 'object' as the dtype, Example -

result1 = np.array(data,'object')

Even though this does result in an array with correct shape , some things may not work because of the mixed types (but I guess you expect that).

Upvotes: 1

Related Questions