breezymri
breezymri

Reputation: 4343

python repeated indexing into a list or a numpy array

I have a set of labels:

>> labels = ['Male', 'Female']

And a list of indices:

>> ii = [0,0,1,0,1,0,1,0,0]

I am trying to get the list of labels corresponding to the indices:

>> labels[ii]

This gave me an error. What I expect to get is:

['Male', 'Male', 'Female', 'Male', 'Female', 'Male', 'Female', 'Male', 'Male']

This is easy in Matlab.

I guess I can use list comprehension:

[labels[i] for i in ii]

Is there another more direct way to get this in python?

Upvotes: 0

Views: 58

Answers (1)

Jan
Jan

Reputation: 1504

If lablels is a numpy array e.g.

labels=numpy.array( ['Male', 'Female'])

you can simply write

labels[ii]

Output is

array(['Male', 'Male', 'Female', 'Male', 'Female', 'Male', 'Female',
       'Male', 'Male'], 
      dtype='|S6')

Upvotes: 2

Related Questions