Create a column by groupby Pandas DataFrame based on tail(1).index


I want create a boolean column that said if a match on first or second half for each match in the dataframe.

#First Half
firsthalf_index = df.groupby(['Date','Match']).apply(lambda x: x[(x.M >= 1) & (x.M <= 45)].tail(1).index)

#Second Half
secondhalf_index = df.groupby(['Date','Match']).apply(lambda x: x[(x.M >= 46) & (x.M <= 90)].tail(1).index)

This code return only the referred.index for each game

enter image description here

What I want to add in this code is df[df.index < firsthalfindex_index] and df[(df.index > firsthalfindex.index) & (df.index < secondhalf_index)]

Asked By: luka



You could do

firsthalf_index = ((df.M >= 1) & (df.M <= 45)).iloc[::-1].groupby([df['Date'],df['Match']]).transform('idxmax')
secondhalf_index =((df.M >= 46) & (df.M <= 90)).iloc[::-1].groupby([df['Date'],df['Match']]).transform('idxmax')


s = df.index.to_series()
df[(s > firsthalf_index) & (s < secondhalf_index)]
Answered By: BENY
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.