Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I rearrange/reorder (not necessarily sort) a pandas dataframe index?

How do I rearrange/reorder (not necessarily sort) a pandas dataframe index?

I have the following dataframe:

df = pd.DataFrame({'A': [1, 2, 3, 4, 5, 6, 7],
                   'B': [0, 1, 0, 2, 1, 7, 1]},
                  index=['Sat', 'Tue', 'Sun', 'Fri',
                         'Wed', 'Mon', 'Thu'])

which gives:

     A  B
Sat  1  0
Tue  2  1
Sun  3  0
Fri  4  2
Wed  5  1
Mon  6  7
Thu  7  1

I want to order the index by day of week (i.e., Sun, Mon, Tue, Wed, Thu, Fri, Sat). The dataframe with the rearranged/reordered index should look something like this:

     A  B
Sun  3  0
Mon  6  7
Tue  2  1
Wed  5  1
Thu  7  1
Fri  4  2

But using df.sort_index() results in an alphabetically-sorted index for df.

How do I explicitly specify the ordering of a dataframe index?

The solution I can think of is to pass the desired index ordering as a list during dataframe creation:

df = pd.DataFrame(df, index=['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri'])

What's another way to do this without creating another dataframe?

Thank you.

like image 332
ralphqq Avatar asked Dec 16 '17 00:12

ralphqq


1 Answers

You can use loc and give it a list of indices in the order that you want them:

df = pd.DataFrame({'A': [1, 2, 3, 4, 5, 6, 7],
                   'B': [0, 1, 0, 2, 1, 7, 1]},
                  index=['Sat', 'Tue', 'Sun', 'Fri',
                         'Wed', 'Mon', 'Thu'])
df = df.loc[['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], :]
df
#      A  B
# Sun  3  0
# Mon  6  7
# Tue  2  1
# Wed  5  1
# Thu  7  1
# Fri  4  2
# Sat  1  0
like image 163
Julien Spronck Avatar answered Oct 19 '22 23:10

Julien Spronck