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

Time:11-20

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

#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

Output 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)]

CodePudding user response:

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

Then

s = df.index.to_series()
df[(s > firsthalf_index) & (s < secondhalf_index)]
  • Related