Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas sort index as an integer

Tags:

python

pandas

I have a data frame which was built out of a CSV. When I am converting this to html using df.to_html() it is giving me a sort order different from the CSV file.

When I print the dataframe on the console it gives me the following output

   reasons_for_make_good
0                   None
1                   None
10                  None
11                  None
12                  None
13                  None
14                  None
15                  None
16                  None
17                  None
18                  None
19                  None
2                   None
3                   None
4                   None
5                   None
6                   None
7                   None
8                   None
9                   None

Why is the index sorted as a string, is it possible to sort it as an integer?

like image 588
Prathik Rajendran M Avatar asked Mar 07 '17 12:03

Prathik Rajendran M


People also ask

How do I sort an index in Pandas?

To sort a Pandas DataFrame by index, you can use DataFrame. sort_index() method. To specify whether the method has to sort the DataFrame in ascending or descending order of index, you can set the named boolean argument ascending to True or False respectively. When the index is sorted, respective rows are rearranged.

What does sort_index do in Pandas?

sort_index() function sorts objects by labels along the given axis. Basically the sorting algorithm is applied on the axis labels rather than the actual data in the dataframe and based on that the data is rearranged.

How do I change the index of a data frame?

To reset the index in pandas, you simply need to chain the function . reset_index() with the dataframe object. On applying the . reset_index() function, the index gets shifted to the dataframe as a separate column.

How can you change the index of a panda series example?

reset_index() function has reset the index of the given Series object to default. It has preserved the index and it has converted it to a column. Example #2: Use Series. reset_index() function to reset the index of the given Series object.


1 Answers

Try convert index to int by Index.astype and then sort_index:

df.index = df.index.astype(int)
df = df.sort_index()
like image 127
jezrael Avatar answered Sep 28 '22 09:09

jezrael