Is there a way to allocates sorted values in a dataframe to groups based on alternating elements

Viewed 76

I have a Pandas DataFrame like:

COURSE  BIB#  COURSE 1  COURSE 2  STRAIGHT-GLIDING     MEAN  PRESTASJON
1          2    20.220    22.535             19.91  21.3775    1.073707
0          1    21.235    23.345             20.69  22.2900    1.077332

This is from a pilot and the DataFrame may be much longer when we perform the real experiment. Now that I have calculated the performance for each BIB#, I want to allocate them into two different groups based on their performance. I have therefore written the following code:

df1 = df1.sort_values(by='PRESTASJON', ascending=True)

This sorts values in the DataFrame. Now I want to assign even rows to one group and odd rows to another. How can I do this?

I have no idea what I am looking for. I have looked up in the documentation for the random module in Python but that is not exactly what I am looking for. I have seen some questions/posts pointing to a scikit-learn stratification function but I don't know if that is a good choice. Alternatively, is there a way to create a loop that accomplishes this? I appreciate your help.

Here a figure to illustrate what I want to accomplish

What I want to accomplish

2 Answers

How about this:

threshold = 0.5
df1['group'] = df1['PRESTASJON'] > threshold

Or if you want values for your groups:

df['group'] = np.where(df['PRESTASJON'] > threshold, 'A', 'B')

Here, 'A' will be assigned to column 'group' if precision meets our threshold, otherwise 'B'.


UPDATE: Per OP's update on the post, if you want to group them alternatively into two groups:

#sort your dataframe based on precision column
df1 = df1.sort_values(by='PRESTASJON')
#create new column with default value 'A' and assign even rows (alternative rows) to 'B'
df1['group'] = 'A'
df1.iloc[1::2,-1] = 'B'

Are you splitting the dataframe alternatingly? If so, you can do:

df1 = df1.sort_values(by='PRESTASJON', ascending=True)

for i,d in df1.groupby(np.arange(len(df1)) %2):
    print(f'group {i}')
    print(d)

Another way without groupby:

df1 = df1.sort_values(by='PRESTASJON', ascending=True)
mask = np.arange(len(df1)) %2

group1 = df1.loc[mask==0]

group2 = df1.loc[mask==1]
Related