Panchi
Panchi

Reputation: 551

Python : creating an array from list with given indices

I know this ought to be simple, but I am still stuck :-/

I have two equal-length arrays a and b. There are three equal-length lists al1, al2, al3 : where I have number pairs such that (a[i],b[i])=(al1[j],al2[j]). I have put all these indices of i and j in aindex and lindex respectively. I want to create another array c (equal to length of array a) containing numbers from al3.

See the code:

import numpy as np

list1 = [9,7,8,2,3,4,1,6,0,7,8]
a = np.asarray(al)
list2 = [5,4,2,3,4,3,4,5,5,2,3]
b = np.asarray(bl)

al1 = [9,4,5,1,7]
al2 = [5,3,6,4,5]
al3 = [5,6,3,4,7]

lindex = [0,5,6]
aindex = [0,1,3]
index = np.asarray(aindex)

c = []
for i in range(0,len(list1)):
    if i in aindex:
    com = al3[i]
else:
    com = 'nan'

c.append(com)

What I get is

c = [5, 6, 'nan', 4, 'nan', 'nan', 'nan', 'nan', 'nan', 'nan', 'nan']

What i want is

c = [5, 'nan', 'nan', 'nan', 'nan', 6, 4, 'nan', 'nan', 'nan', 'nan']

Please help :-/

Upvotes: 0

Views: 184

Answers (1)

Claudiu
Claudiu

Reputation: 229361

I must admit I have no clue what you're doing, but what you seem to want is this:

>>> c = ['nan'] * len(a)
>>> for i, j in zip(aindex, lindex):
...     c[j] = al3[i]
... 
>>> c
[5, 'nan', 'nan', 'nan', 'nan', 6, 4, 'nan', 'nan', 'nan', 'nan']

They way it works is by first initializing c to be a list of length a containing all nans:

>>> c = ['nan'] * len(a)
>>> c
['nan', 'nan', 'nan', 'nan', 'nan', 'nan', 'nan', 'nan', 'nan', 'nan', 'nan']

What zip does is pair together the elements of each list:

>>> zip(aindex, lindex)
[(0, 0), (1, 5), (3, 6)]

So I iterate through each pair, taking the value of al3 at the first index and assigning it into c at the second index. Anything that is unassigned remains 'nan'.

Upvotes: 2

Related Questions