在Python中转换列索引

2024-09-26 22:51:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据帧:

   index    PUBLICO     CLASSIFICACAO_PUBLICO
0   19      143643          1
1   34      111879          2
2   31       50382          3
3   9        49204          4
4   32       37541          5
5   4        36095          6

我需要将索引名列转换为索引列。你知道吗

例如:

index   PUBLICO     CLASSIFICACAO_PUBLICO
19      143643          1
34      111879          2
31       50382          3
9        49204          4
32       37541          5
4        36095          6

我试着用df.set_index('index'),但没用。你知道吗

以前名为index的列是DataFrame的索引列,但我使用了reset_index();现在我需要做相反的操作。你知道吗


Tags: 数据dataframedfindexresetset名列classificacao
2条回答

方法set_index不适用。因此您必须重新分配数据帧,或者传递选项inplace = True

df = df.set_index('index')

或者

df.set_index('index',inplace = True)

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html

您可以这样尝试:

df.set_index(df['index'], inplace=True)

这会将index列设置为数据帧中的索引,并且index列也会保留在数据帧中。然后,你就可以放下那一栏。你知道吗

df.drop('index', axis=1, inplace=True)

相关问题 更多 >

    热门问题