Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match nested list with dataframe

Tags:

python

pandas

I have a nested list as shown below,

[['a'], ['b'], [], ['d', 'a'], ['c', 'd', 'a']]

I also have a dataframe which maps letters with a value, i.e.

  col1  value
0    a      2
1    b      5
2    c      4
3    d      9

My goal is to match the letters in the list with the data frame and return the corresponding value. Where there are more than 1 letters, I need the sum of their values. My expected result is a flat list as shown below,

[2, 5, 0, 11, 15]

I tried doing a for loop but could not get it to work.

for i in l1:
    if len(i) == 0:
        print(0)
    elif len(i) > 1:
        for j in i:
            print(d1[d1['col1'] == j]['value'])
    else:
        print(d1[d1['col1'] == i]['value'])

Also, efficiency is key here since the data set is huge

Data

l1 = [['a'], ['b'], [], ['d', 'a'], ['c', 'd', 'a']]
d1 = pd.DataFrame({'col1':['a', 'b', 'c', 'd'], 'value':[2, 5, 4, 9]})

Session Details

print(sys.version)
3.6.1 |Anaconda 4.4.0 (64-bit)| (default, May 11 2017, 13:25:24) [MSC v.1900 64 bit (AMD64)]
like image 282
Sotos Avatar asked Aug 13 '26 15:08

Sotos


1 Answers

IIUC for loop with isin

[d1.loc[d1.col1.isin(x),'value'].sum()for x in l1]
Out[883]: [2, 5, 0, 11, 15]
like image 52
BENY Avatar answered Aug 16 '26 05:08

BENY