Jason S
Jason S

Reputation: 189726

pandas converting numbers to corresponding elements of a list

Let's say I have a series of numbers and a list:

s1 = pd.Series([0,1,2,5,4,1,0,2])
mylist = pd.Series(['apples','pears','bananas','oranges','lemons','limes'])

and I want to create a new series with values looked up using the list. If I do mylist[s1] the values are correct but the indices are wrong:

>>> mylist[s1]
0     apples
1      pears
2    bananas
5      limes
4     lemons
1      pears
0     apples
2    bananas
dtype: object

and I can do this to get the correct answer, but it seems cumbersome:

>>> pd.Series(mylist[s1].values, index=s1.index)
0     apples
1      pears
2    bananas
3      limes
4     lemons
5      pears
6     apples
7    bananas
dtype: object

Is there a more idiomatic way to do this?

Upvotes: 0

Views: 50

Answers (1)

unutbu
unutbu

Reputation: 879869

In [177]: s1.map(mylist)
Out[177]: 
0     apples
1      pears
2    bananas
3      limes
4     lemons
5      pears
6     apples
7    bananas
dtype: object

Series.map is quite versatile -- not only does it accept sequences, it can also take a callable (like the Python built-in, map), or a Series or a dict.

Upvotes: 2

Related Questions