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)?
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'}
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