pandas 如何在pandas df中设置新索引并删除默认索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42614049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:07:24  来源:igfitidea点击:

How to set new index and remove default index in pandas df

pythonpandasdataframe

提问by kshama

I have attached the dataframe in the pic. In the df, subVoyageID is the default index, I am trying to remove that blank row next to the subvoyageID, so that all the column names are aligned in the same row, but I am unable to do it.

我已在图片中附加了数据框。在 df 中,subVoyageID 是默认索引,我试图删除 subvoyageID 旁边的空白行,以便所有列名都在同一行中对齐,但我无法这样做。

Since subVoyageID is the default index, I copied the data into new col "svid" and reset the index to new column "svid", (see the code and pic below)

由于 subVoyageID 是默认索引,我将数据复制到新列“svid”并将索引重置为新列“svid”,(请参阅下面的代码和图片)

    df["SVID"] = df.index
    df.set_index('SVID')
    df

Original df

原始文件

orig df

原始文件

Resultant df

结果 df

new df

新的df

Now how do I get rid of the very first column which was the default index, as df.info() shows 5 columns from x-max to SVID; Or is there any other way I could align all the column labels in one row. Thanks for any help.

现在我如何摆脱作为默认索引的第一列,因为 df.info() 显示了从 x-max 到 SVID 的 5 列;或者有没有其他方法可以将所有列标签对齐在一行中。谢谢你的帮助。

回答by jezrael

Use reset_indexfor convert index values to column and if necessary renamecolumn:

使用reset_index了转换指数值列,并在必要时rename柱:

df = df.reset_index().rename(columns={'subVoyageID':'SVID'})

回答by miradulo

That's because subVoyageIDisn't a column, it is your index. Just use reset_index()to make it an actual column.

那是因为subVoyageID它不是,而是您的索引。只是reset_index()用来使它成为一个实际的列。

Example

例子

>>> df

         a  b  c
myindex         
0        0  1  2
1        3  4  5
2        6  7  8

>>> df.reset_index().rename(columns={df.index.name: 'not my index'})

   not my index  a  b  c
0             0  0  1  2
1             1  3  4  5
2             2  6  7  8