如何删除熊猫数据框中的自动索引?

时间:2021-02-16 04:44:42

标签: python python-3.x pandas dataframe

如何删除 pandas 数据框中的自动索引?删除索引不起作用。 所以当我使用 df.iloc[0:4]['col name'] 时,它总是返回两列,一列用于我需要的实际数据,一列用于自动行索引。我怎样才能摆脱自动索引并只返回我需要的列?

这就是 iloc[0:4]['col name'] 返回的内容:

<头>
0 id2
1 id2
2 id1
3 id3

以下是我真正想要的:

<头>
id2
id2
id1
id3

1 个答案:

答案 0 :(得分:1)

如果您在 JupyterLab / Jupyter Notebook 中工作,请使用命令

iloc[0:4]['col name'].style.hide_index()

解释:

数据帧总是有一个索引,没有办法删除它,因为它是每个数据帧的核心部分

iloc[0:4]['col name'] 也是一个数据框。)

您只能在输出中隐藏它。

例如在 JupyterLab(或 Jupyter Notebook)中,您可以使用命令显示没有索引的数据帧(df

df.style.hide_index()          # in your case: iloc[0:4]['col name'].style.hide_index()

小心 - df.style.hide_index() 不是数据帧(它是一个 Styler 对象),所以不要将它分配回 df

        # df = df.style.hide_index()       # Don't do it, never!

一个数据帧输出的例子——首先有索引,然后没​​有索引:

enter image description here