william007
william007

Reputation: 18545

Map columns with list and return corresponding list

import pandas as pd

pd.DataFrame({"a":["a","b","c"],"d":[1,2,3]})

Given an array ["a","b","c","c"], I want it to use to map col "a", and get output [1,2,3,3] which is from column "d". Is there a short way to do this without iterating the rows?

Upvotes: 1

Views: 25

Answers (1)

jezrael
jezrael

Reputation: 862911

Use Series.reindex with index by a converted to index by DataFrame.set_index:

a = ["a","b","c","c"]

L = df.set_index('a').reindex(a)['d'].tolist()
print (L)
[1, 2, 3, 3]

Upvotes: 1

Related Questions