I have a DataFrame in which I'm attempting to reverse the row order if a condition is met.
The DataFrame (df) is:
name id description
0 a String 1 lion
1 b String 1 snake
2 c String 1 bear
3 d String 1 tiger
4 e String 1 dog
5 f String 2 cat
6 g String 2 bird
7 h String 2 whale
8 i String 2 eagle
9 j String 2 rhino
10 k String 3 monkey
11 l String 3 lamb
12 m String 3 horse
13 n String 3 goat
14 o String 3 rabbit
15 p String 4 frog
16 q String 4 jaguar
17 r String 4 fox
18 s String 4 sloth
19 t String 4 beaver
20 u String 5 parrot
21 v String 5 dolphin
22 w String 5 seal
23 x String 5 spider
24 y String 5 panda
For the df ['id'] rows that equal String 2 and String 4 (essentially all id's that are % 2 == 0) I would like to reverse the order of the rows in that group. The output DataFrame I am looking for would be:
name id description
0 a String 1 lion
1 b String 1 snake
2 c String 1 bear
3 d String 1 tiger
4 e String 1 dog
**5 j String 2 rhino**
**6 i String 2 eagle**
**7 h String 2 whale**
**8 g String 2 bird**
**9 f String 2 cat**
10 k String 3 monkey
11 l String 3 lamb
12 m String 3 horse
13 n String 3 goat
14 o String 3 rabbit
**15 t String 4 beaver**
**16 s String 4 sloth**
**17 r String 4 fox**
**18 q String 4 jaguar**
**19 p String 4 frog**
20 u String 5 parrot
21 v String 5 dolphin
22 w String 5 seal
23 x String 5 spider
24 y String 5 panda
I am capable of doing this individually with:
df.loc[df['id'] == 'condition'][::-1]
I am struggling with how to apply it to the DataFrame so that it modifies it. I have tried the following function to no avail:
def reversal(row):
for row in df.id:
if row == 'condition':
return df.loc[df['id'] == 'condition'][::-1]
It's my intent to utilize this on a DataFrame of about 30K rows. Which really isn't that much but I'm still mindful of trying to use the most efficient approach.
It is equally important to me to understand the logic that is behind the solution as I'm just really starting to learn Python. I think the code above is a good tell of that being so.
Thank you for any help, I'm kinda stumped on this one.