Prathik Rajendran M
Prathik Rajendran M

Reputation: 1162

Pandas sort index as an integer

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?

Upvotes: 13

Views: 6296

Answers (1)

jezrael
jezrael

Reputation: 863146

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

df.index = df.index.astype(int)
df = df.sort_index()

Upvotes: 16

Related Questions