Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map Values from List of Lists to Pandas Dataframe Column

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!

like image 675
lucas winter Avatar asked Dec 30 '22 14:12

lucas winter


2 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
like image 78
Andrej Kesely Avatar answered Jan 02 '23 03:01

Andrej Kesely


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
like image 43
BENY Avatar answered Jan 02 '23 02:01

BENY