Wendy D.
Wendy D.

Reputation: 109

Conditionally select by matching values of a dictionary to columns of a data frame python

I have a dictionary as below:

dict = {0: [a,b,d,c],
        3:[w,v,t,e],...}

A data frame as below:

col1   col2   col3
a      d      10
a      b      5
a      c      20
b      a      5
b      d      3
b      c      8
d      a      10
d      b      3
d      c      12
c      a      20
c      b      8
c      d      12

I want to map each unique combination in the values of dictionary to match col1 and col2, then select col3 and append the key. Results should as below:

col1 col2 col3 key
a    b    5     0
a    d    10    0
a    c    20    0
b    d    3     0
b    c    8     0
d    c    12    0

Upvotes: 1

Views: 165

Answers (1)

yatu
yatu

Reputation: 88275

You can obtain the combinations from the dictionary lists itertools.combinations, build a dataframe from the flattened list of length 2 combinations, and merge with the dataframe:

from itertools import combinations

d = {0: ['a','b','d','c'],
     3: ['w','v','t','e']}

combs = [(k,*i) for k,v in d.items() for i in list(combinations(v, r=2))]
# [(0, 'a', 'b'), (0, 'a', 'd'), (0, 'a', 'c')...
pd.DataFrame(combs, columns=['key','col1','col2']).merge(df, on=['col1','col2'])

  key col1 col2  col3
0   0    a    b     5
1   0    a    d    10
2   0    a    c    20
3   0    b    d     3
4   0    b    c     8
5   0    d    c    12

Upvotes: 1

Related Questions