Python 从两个字段创建字典字段
假设我有一个数据帧,如:Python 从两个字段创建字典字段,python,pandas,dictionary,Python,Pandas,Dictionary,假设我有一个数据帧,如: 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 我可以使用df.groupby('time)[
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
我可以使用df.groupby('time)['action']]创建操作列表。apply(list)
我想创建一个在时间
聚合的字段,并从操作
/播放器
创建一个字典
因此,预期产出为:
time action ...[other fields]
----------------------------------------------
10:00 {A:Buy,B:Hold}
09:45 {A:[Sell,Hold],B:Buy}
09:30 {A:Hold}
也许类似于
df.groupby('time)['action'].apply(dict,player=action)
?你很接近了……只要在你groupby
时设置索引为player,然后agg(dict)
你就有了适合你的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'}
为我工作!不知道为什么。。。要求对这种情况是如何发生的/为什么发生的进行简要解释是否太过分了?是因为Pandas在创建字典字段时将索引识别为键吗???@Samcd,这是正确的。使用dict
agg
时,熊猫将使用索引作为键,列作为值。这类似于使用pd.Series.to_dict()
,它将使用帧的索引作为键。