Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Dictionary Field From Two Pandas Fields

Let's say I have a data frame like:

time    action    player    ...[other fields]
----------------------------------------------
10:00   Buy       A
10:00   Hold      B
09:45   Sell      A
09:45   Buy       B
09:45   Hold      A
09:30   Hold      A

I am able to create a list of actions with df.groupby('time)['action'].apply(list)

I want to create a field that aggregates on time and creates a dictionary from action/player.

So expected output is:

 time    action    ...[other fields]
----------------------------------------------
10:00   {A:Buy,B:Hold}
09:45   {A:[Sell,Hold],B:Buy}
09:30   {A:Hold}

Maybe something like df.groupby('time)['action'].apply(dict,player=action)?

like image 755
Sam cd Avatar asked Sep 15 '26 04:09

Sam cd


1 Answers

You are close...just set_index to player that way when you groupby, and agg(dict) you have the appropriate keys for your dict.

df.set_index('player').groupby('time')['action'].agg(dict)

time
09:30                          {'A': 'Hold'}
09:45    {'A': ['Sell', 'Hold'], 'B': 'Buy'}
10:00              {'A': 'Buy', 'B': 'Hold'}
like image 54
It_is_Chris Avatar answered Sep 16 '26 19:09

It_is_Chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!