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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With