Map Values from List of Lists to Pandas Dataframe Column

Viewed 990

I have a list of lists in the following format:

l = [[1,2,3,4], [5,6], [7], [8,9,10]]

and a pandas dataframe with the following column

Value
1
3
5
9

My goal is to loop through every row in the value column in the dataframe to find what list the value is in. I'd like to create a new column with the first value from the list that the value is in. The result would look something like this.

Value List_Val
1 1
3 1
5 5
9 8

Any help would be greatly appreciated. Thanks!

3 Answers

Try:

l = [[1, 2, 3, 4], [5, 6], [7], [8, 9, 10]]

df["List_Val"] = df["Value"].apply(
    lambda x: next((subl[0] for subl in l if x in subl), np.nan)
)

print(df)

Prints:

   Value  List_Val
0      1         1
1      3         1
2      5         5
3      9         8

Try with explode then map

s = pd.Series(l).explode()
s.index = s.groupby(level=0).transform('first')
df['List_val'] = df['Value'].map(dict(zip(s,s.index)))
df
Out[36]: 
   Value  List_val
0      1         1
1      3         1
2      5         5
3      9         8

Let's use dictionary comprehension and map:

df['list_val'] = df['Value'].map({v:i[0] for i in l for v in i})

Output:

   Value  list_val
0      1         1
1      3         1
2      5         5
3      9         8
Related