Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将索引列转换为数字?_Python_Pandas - Fatal编程技术网

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