Reputation: 379
Hi all so I have the following column in my dataframe:
LC_REF
1 DT 16 2C
2 DT 16 2C
3 DT 16 2C
1 DT 16 3C
6 DT 16 3C
3 DT 16 3C
7 DT 16 3C
0 DT 17 1C
0 DT 17 1C
0 DT 17 1C
1 DT 17 1C
0 DT 17 2C
2 DT 17 2C
4 DT 17 2C
5 DT 17 2C
4 DT 17 3C
1 DT 17 3C
8 DT 17 3C
And I'm wondering if its possible to organize every group of LC_REF's such that the index is in ascending order:
LC_REF
1 DT 16 2C
2 DT 16 2C
3 DT 16 2C
1 DT 16 3C
3 DT 16 3C
6 DT 16 3C
7 DT 16 3C
0 DT 17 1C
0 DT 17 1C
0 DT 17 1C
1 DT 17 1C
0 DT 17 2C
2 DT 17 2C
4 DT 17 2C
5 DT 17 2C
1 DT 17 3C
4 DT 17 3C
8 DT 17 3C
so far I have tried:
df.groupby('LC_REF').apply(pd.DataFrame.sort_index,'LC_REF',1)
grouped = df.groupby('LC_REF').sum().reset_index()
but that does not give the correct output.
Upvotes: 2
Views: 49
Reputation: 323386
Or As my comment , that is the 1st good way to go . But if you you do want to using groupby
try this
df.groupby('LC_REF',as_index=False).apply(pd.DataFrame.sort_index)
Upvotes: 0
Reputation: 7977
df = pd.read_table(StringIO("""
id LC_REF
1 DT 16 2C
2 DT 16 2C
3 DT 16 2C
1 DT 16 3C
6 DT 16 3C
3 DT 16 3C
7 DT 16 3C
0 DT 17 1C
0 DT 17 1C
0 DT 17 1C
1 DT 17 1C
0 DT 17 2C
2 DT 17 2C
4 DT 17 2C
5 DT 17 2C
4 DT 17 3C
1 DT 17 3C
8 DT 17 3C"""), sep = ' ')
df.sort_values(['LC_REF', 'id'],ascending=True)
Upvotes: 1
Reputation: 863651
I think better is use reset_index
for column from index
, then sort_values
and last set_index
:
df = df.reset_index().sort_values(['LC_REF','index']).set_index('index').rename_axis(None)
print (df)
LC_REF
1 DT 16 2C
2 DT 16 2C
3 DT 16 2C
1 DT 16 3C
3 DT 16 3C
6 DT 16 3C
7 DT 16 3C
0 DT 17 1C
0 DT 17 1C
0 DT 17 1C
1 DT 17 1C
0 DT 17 2C
2 DT 17 2C
4 DT 17 2C
5 DT 17 2C
1 DT 17 3C
4 DT 17 3C
8 DT 17 3C
Upvotes: 3