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?
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.
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.
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.
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.
Try convert index to int
by Index.astype
and then sort_index
:
df.index = df.index.astype(int)
df = df.sort_index()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With