我正在使用基于事件的数据,希望仅返回按特定顺序的行。下面是一个序列和数据结构的示例。
我的问题是要返回这样的序列,其想法是搜索action_name列以查找目标条目,然后返回导致目标达成的每个通过/动作。链接动作的方式是通过possesion_number和match_id,因为它们对于每个序列都是唯一的。
我可以通过使用以下代码将所有通过和目标操作返回到单独的数据框中来完成第一部分,但是如何保留仅以目标结尾的序列?
pass_goal = data.loc[data.action_name.isin(['Attacking pass accurate',
'Non attacking pass accurate','Accurate key pass','goal'])]
我认为有更好的方法来解决这个问题。首先,合计达到所有物的级别,保留动作并以某种方式对其进行排序(second
?)
posses = data.groupby('possession_number')[['second', 'action_name']].apply(lambda action: action.values.tolist()).reset_index(name='action_seq')
然后,对其中的操作进行排序,并确定最后一个操作是目标的操作。
posses['ends_in_goal'] = posses.apply(lambda pos: sorted(pos['action_seq'])[-1][1] == 'goal', axis=1)
编辑:
为了明确起见,该apply
方法在(在本例中为axis=1
)行上评估函数,并将输出分配给新列。这是带有突破的功能:
lambda pos: # Define a lambda with the row as "pos"
sorted(pos['action_seq']) # Sort the "action_seq" list of tuples by the first tuple value, "second" (see above)
[-1][1] # Get the last tuple in the sorted list of tuples, and from the last tuple, get the second value, "action_name"
== 'goal' # Return True if the "action_name" of the last tuple in the sorted list of actions for that possession is "goal"
如果要按其他列对所有资产中的动作进行排序,请创建该列作为第一个元组值的元组列表(请参见['second', 'action_name']
上文。),然后action_name
从元组中的适当位置获取其值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句