0

I have a dataframe, column 1 contains the name of the states. Column 2 contains the city. Column 3, 4, 5...contains data I'm interested in for each city. Right now, the order of rows is random. I'd like to group the rows so that cities that are in the same states are grouped together.

For example, After the ordering, data will look like this:


Pennsylvania, Bryn Mawr, 33, 283, 392
Pennsylvania, Philadelphia, 37, 373, 328
Pennsylvania, Pittsburgh, 37, 483, 479

Ohio, Columbus, 382, 830, 281
Ohio, Hudson, 291, 39, 10

Before ordering the rows are in random order. Any idea would be appreciated!

Sayandip Dutta
  • 15,602
  • 4
  • 23
  • 52
Tianhe Xie
  • 261
  • 1
  • 10
  • `df.sort_values([col1,col2])` ? – Umar.H Jul 28 '20 at 10:10
  • Does this answer your question? [how to sort pandas dataframe from one column](https://stackoverflow.com/questions/37787698/how-to-sort-pandas-dataframe-from-one-column) – Heikura Jul 28 '20 at 10:11

2 Answers2

2

You should try df.sort_values(by=['your column name'])

Here find full documentation of sort_values method : https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html

Vincent
  • 46
  • 1
1

You can use sort_values :

df = df.sort_values(by =['State'] )