0

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 :-/

2
  • 1
    can you fix up your indentation? Commented Sep 24, 2013 at 15:27
  • @claudiu: we have a(0),b(0) = al1(0),al2(0) and a(5),b(5) = al1(1),al2(1) and so on... for these similar values, 'lindex' is the list of indices in a and b and 'aindex' the list of indices in al1, al2. :-/ Commented Sep 24, 2013 at 15:33

1 Answer 1

2

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'.

Sign up to request clarification or add additional context in comments.

1 Comment

yes, that works.. i didn't know it could be so simple :) thank you thank you :) i will 'accept' the answer the moment i can do it (they say it can be done in 4 mins) :)

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.