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
How to set new index and remove default index in pandas df
提问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
原始文件
Resultant 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_index
for convert index values to column and if necessary rename
column:
使用reset_index
了转换指数值列,并在必要时rename
柱:
df = df.reset_index().rename(columns={'subVoyageID':'SVID'})
回答by miradulo
That's because subVoyageID
isn'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