Mapping Dictionary Values to Pandas Data-frame Column

  • A+
Category:Languages

I have this dictionary:

 j =  {1: {'help': 2},  2: {'chocolate': 1, 'help': 1},  3: {'chocolate': 1, 'help': 1}} 

and this dataframe:

df = pd.DataFrame({'docId': [1, 2, 3, 1, 2, 3, ],                        'sent': ['help', 'chocolate', 'chocolate', 'help', 'help', 'help']}) 

and I want to match the values according to docId and term so it should look like this:

docId  sent        freq 1      help         2 2      chocolate    1 3      chocolate    1 1      help         2 2      help         1 3      help         1 

I'm not sure how to accomplish this, I was working on using map and apply but I didn't get anywhere.

 


Remake your dictionary

With tuples as keys, you can map the get method over zipped columns

J = {(x, y): v for x, V in j.items() for y, v in V.items()}  df.assign(freq=[*map(J.get, zip(df.docId, df.sent))])      docId       sent  freq 0      1       help     2 1      2  chocolate     1 2      3  chocolate     1 3      1       help     2 4      2       help     1 5      3       help     1 

Or don't

You can use a lambda in map that takes two arguments and pass the iterables that supply the arguments.

df.assign(freq=[*map(lambda x, y: j[x][y], df.docId, df.sent)])     docId       sent  freq 0      1       help     2 1      2  chocolate     1 2      3  chocolate     1 3      1       help     2 4      2       help     1 5      3       help     1 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: