Tristan Andrews
Tristan Andrews

Reputation: 3

How to sort the order of index for value_counts() to a custom order?

After performing value_counts() to a series in a dataframe,

>>> n_fires_by_month = df['month'].value_counts()
>>> n_fires_by_month

I get this:

| -------| -------------- |
| aug    | 184            |
| sep    | 172            |
| mar    | 54             |
| jul    | 32             |
| feb    | 20             |
| jun    | 17             |
| oct    | 15             |
| dec    | 9              |
| apr    | 9              |
| may    | 2              |
| jan    | 2              |
| nov    | 1              |

After running value_counts(), I want to reset the index of the resulting table in order of month so I want the resulting table to look like this:

| -------| -------------- |
| jan    | 2              |
| feb    | 20             |
| mar    | 54             |
| apr    | 9              |
| may    | 2              |
| jun    | 17             |
| jul    | 32             |
| aug    | 184            |
| sep    | 172            |
| oct    | 15             |
| nov    | 1              |
| dec    | 9              |

Please help.

Upvotes: 0

Views: 2331

Answers (3)

Silvano
Silvano

Reputation: 11

After a quick Google search, I found this: https://www.codegrepper.com/code-examples/typescript/pandas+value_counts+sort

So this should work for you:

n_fires_by_month = df['month'].value_counts().sort_index()

Upvotes: 1

DYZ
DYZ

Reputation: 57033

Using the days' abbreviations from the module calendar, reindex the dataframe. No explicit sorting is needed:

abbr_months = [x.lower() for x in calendar.month_abbr][1:]
df.set_index('month').reindex(abbr_months)
#jan    2
#feb   20
#mar   54
#apr    9
#may    2
#jun   17
#jul   32
#aug  184
#sep  172
#oct   15
#nov    1
#dec    9

Upvotes: 3

Aditya
Aditya

Reputation: 1377

You can convert the months to a datetime object and then sort like this:

df['month_dt'] = pd.to_datetime(df['month'], format='%b')
df = df.sort_values(by='month_dt')

Output:

    month   Count   month_dt
10  jan     2      1900-01-01
4   feb     20     1900-02-01
2   mar     54     1900-03-01
8   apr     9      1900-04-01
9   may     2      1900-05-01
5   jun     17     1900-06-01
3   jul     32     1900-07-01
0   aug     184    1900-08-01
1   sep     172    1900-09-01
6   oct     15     1900-10-01
11  nov     1      1900-11-01
7   dec     9      1900-12-01

Upvotes: 0

Related Questions