简体   繁体   中英

How to convert index column to numeric?

I have a dataframe whose index row is string data type. I want it to be numeric and sorted:

  col1 col2
1  25   33
3  35  544
2  24   52

expected :

  col1 col2
1  25   33
2  24   52
3  35   544

First, convert and assign with pd.to_numeric .

df.index = pd.to_numeric(df.index, errors='coerce')

To sort the DataFrame by its index, call df.sort_index :

df.sort_index()

   col1  col2
1    25    33
2    24    52
3    35   544

You can specify inplace=True for the second command, if you want an inplace operation, or you can pass it down the pipeline.

You could use astype and sort_index

In [833]: df.index
Out[833]: Index([u'1', u'3', u'2'], dtype='object')

In [834]: df.index = df.index.astype(int)

In [837]: df = df.sort_index()

In [838]: df
Out[838]:
   col1  col2
1    25    33
2    24    52
3    35   544

In [839]: df.index
Out[839]: Int64Index([1, 2, 3], dtype='int64')

Or , a single liner using set_index

In [851]: df.set_index(df.index.astype(int)).sort_index()
Out[851]:
   col1  col2
1    25    33
2    24    52
3    35   544

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM