如何将索引列转换为数字?

kan*_*and 3 python pandas

我有一个数据框,其索引行是字符串数据类型。我希望它是数字并排序的:

  col1 col2
1  25   33
3  35  544
2  24   52
Run Code Online (Sandbox Code Playgroud)

预期的 :

  col1 col2
1  25   33
2  24   52
3  35   544
Run Code Online (Sandbox Code Playgroud)

cs9*_*s95 5

首先,使用 进行转换和赋值pd.to_numeric

df.index = pd.to_numeric(df.index, errors='coerce')
Run Code Online (Sandbox Code Playgroud)

要按索引对 DataFrame 进行排序,请调用df.sort_index

df.sort_index()

   col1  col2
1    25    33
2    24    52
3    35   544
Run Code Online (Sandbox Code Playgroud)

如果您想要就地操作,您可以指定inplace=True第二个命令,也可以将其传递到管道中。