Reputation: 103
I have 2 dataframes with the same column names, for example:
col1 col2 col3
1 2 3
and
col1 col2 col3
4 5 6
1 7 8
I have appended them, so now the new dataframe is like below:
col1 col2 col3
1 2 3
4 5 6
1 7 8
The problem is that I need the rows that have the same value in the col1 to come one after the other, just like this:
col1 col2 col3
1 2 3
1 7 8
4 5 6
How can I sort the dataframe by col1 to create this effect(without modifying the dataframe type)?
Upvotes: 0
Views: 36
Reputation: 580
You can sort a DataFrame by any column, for example:
df.sort_values(by=['col_1', 'col_2'], ascending=[True, False], inplace=True)
After that you may like to reset the row index, as they will be jumbled up:
df.reset_index(drop=True, inplace=True)
Upvotes: 0
Reputation: 1061
if you care about ensuring that dataframe 1 values are sorted before dataframe 2 values where they are tied, you can use the 'mergesort' algorithm. The default algorithm will arbritarily order any tied values.
df.sort_values(by='col1', axis=1, ascending=True, inplace=True, kind='mergesort')
Upvotes: 1
Reputation: 863166
df = pd.concat([df1, df2]).sort_values('col1', ignore_index=True)
Upvotes: 1