Grothen
Grothen

Reputation: 33

How to split list into numpy array?

A basic question about populating np arrays from a list:

m is a numpy array with shape (4,486,9).

d is a list with length 23328 and a varying number of items for each index.

I am iterating through m on dimension 1 and 2 and d on dimension 1.

I want to import 9 "columns" from particular lines of d at constant intervals, into m. 6 of those columns are successive, they are shown below with index "some_index".

What I have done below works okay but looks really heavy in syntax, and just wrong. There must be a way to export the successive columns more efficiently?

import numpy as np
m=np.empty(4,486,9)
d=[] #list filled in from files
#some_index is an integer incremented in the loops following some        conditions
#some_other_index is another integer incremented in the loops following some other conditions
For i in something:
    For j in another_thing:
        m[i][j]=[d[some_index][-7], d[some_index][-6], d[some_index][-5], d[some_index][-4], d[some_index][-3], d[some_index][-2], d[some_other_index][4], d[some_other_index][0], d[some_other_index][4]]

Without much imagination, I tried the followings which do not work as np array needs a coma to differentiate items:

For i in something:
    For j in another_thing:
        m[i][j]=[d[some_index][-7:-1], d[some_other_index][4], d[some_other_index][0], d[some_other_index][4]]
ValueError: setting an array element with a sequence.

        m[i][j]=[np.asarray(d[some_index][-7:-1]), d[some_other_index][4], d[some_other_index][0], d[some_other_index][4]]
ValueError: setting an array element with a sequence.

Thanks for your help.

Upvotes: 0

Views: 510

Answers (1)

Clock Slave
Clock Slave

Reputation: 7967

Is this what you are looking for?

You can make use of numpy arrays to select multiple elements at once.

I have taken the liberty to create some data in order to make sure we are doing the right thing

import numpy as np
m=np.zeros((4,486,9))
d=[[2,1,2,3,1,12545,45,12], [12,56,34,23,23,6,7,4,173,47,32,3,4], [7,12,23,47,24,13,1,2], [145,45,23,45,56,565,23,2,2],
   [54,13,65,47,1,45,45,23], [125,46,5,23,2,24,23,5,7]] #list filled in from files
d = np.asarray([np.asarray(i) for i in d]) # this is where the solution lies
something = [2,3]
another_thing = [10,120,200]
some_index = 0
some_other_index = 5
select_elements = [-7,-6,-5,-4,-3,-2,4,0,4] # this is the order in which you are selecting the elements

for i in something:
    for j in another_thing:
        print('i:{}, j:{}'.format(i, j))
        m[i,j,:]=d[some_index][select_elements]

Also, I noticed you were indexing this way m[i][j] = .... You can do the same with m[i,j,:] = ...

Upvotes: 1

Related Questions