Python 如何将索引列转换为数字?
我有一个数据帧,其索引行是字符串数据类型。我希望它是数字和排序:Python 如何将索引列转换为数字?,python,pandas,Python,Pandas,我有一个数据帧,其索引行是字符串数据类型。我希望它是数字和排序: col1 col2 1 25 33 3 35 544 2 24 52 预期: col1 col2 1 25 33 2 24 52 3 35 544 首先,用pd.转换并分配到\u numeric df.index = pd.to_numeric(df.index, errors='coerce') 要按索引对数据帧进行排序,请调用df.sort\u index: df.sort_in
col1 col2
1 25 33
3 35 544
2 24 52
预期:
col1 col2
1 25 33
2 24 52
3 35 544
首先,用
pd.转换并分配到\u numeric
df.index = pd.to_numeric(df.index, errors='coerce')
要按索引对数据帧进行排序,请调用df.sort\u index
:
df.sort_index()
col1 col2
1 25 33
2 24 52
3 35 544
如果需要一个就地操作,您可以为第二个命令指定
inplace=True
,也可以将其沿管道传递。您可以使用astype
和排序索引
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')
In [851]: df.set_index(df.index.astype(int)).sort_index()
Out[851]:
col1 col2
1 25 33
2 24 52
3 35 544
或,使用设置索引的单行程序
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')
In [851]: df.set_index(df.index.astype(int)).sort_index()
Out[851]:
col1 col2
1 25 33
2 24 52
3 35 544