1

I have a DataFrame, where rows are 'grouped' by the third column (rows in one 'group' have the same value at the third column):

c1 c2 c3
0   b  1
1   r  1
2   f  2
3   x  2
4   n  2
5   r  3
6   f  3

But the values in the second column have a wrong order. I need to reverse rows in each 'group', so DataFrame should look like this:

c1 c2 c3
0   r  1
1   b  1
2   n  2
3   x  2
4   f  2
5   f  3
6   r  3

Is there an effective way to transform the first DataFrame to the second one with pandas?

UPD: Updated with more clear example. The values should be exactly reversed, not just became located in the alphabetical order.

1 Answer 1

3

It seems you need sort_values:

df = df.sort_values(['c3','c2'])
print (df)
   c1   c2  c3
1   1    a   1
0   0    b   1
4   4   aa   2
3   3   bb   2
2   2   cc   2
6   6  xxx   3
5   5  zzz   3

EDIT:

You can use groupby and change order by [::-1]:

#more general solution, working with not unique index also
def reversing(x):
    x['c2'] = x['c2'].iloc[::-1].values
    return x

df = df.groupby('c3', sort=False)).apply(reversing)
print (df)
   c1 c2  c3
0   0  r   1
1   1  b   1
2   2  n   2
3   3  x   2
4   4  f   2
5   5  f   3
6   6  r   3

#solution working only with unique monotonic increasing index, because reset index
df['c2'] = df.groupby('c3', sort=False)['c2'].apply(lambda x: x[::-1]).reset_index(drop=True)
print (df)
   c1 c2  c3
0   0  r   1
1   1  b   1
2   2  n   2
3   3  x   2
4   4  f   2
5   5  f   3
6   6  r   3

Solutions, where order of values in c1 is changed:

You can sorting by index (has to be unique monotonic increasing).

df=df.reset_index().sort_values(['c3','index'],ascending=[True, False]).drop('index',axis=1)
print (df)
   c1 c2  c3
1   1  r   1
0   0  b   1
4   4  n   2
3   3  x   2
2   2  f   2
6   6  f   3
5   5  r   3

If column c1 is unique monotonic increasing (0,1,2..) as default index:

df = df.sort_values(['c3','c1'], ascending=[True, False])
print (df)
   c1 c2  c3
1   1  r   1
0   0  b   1
4   4  n   2
3   3  x   2
2   2  f   2
6   6  f   3
5   5  r   3
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer, but these letters are just an example of values, sorry that I've incorrectly cited this example. In my case the values in the groups shouldn't be in alphabetical order, they should be exactly reversed. I've updated the post with more clear example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.