如何在 pandas df中设置新索引并删除默认索引 [英] How to set new index and remove default index in pandas df

查看:528
本文介绍了如何在 pandas df中设置新索引并删除默认索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

由于subVoyageID是默认索引,因此我将数据复制到了新列"svid"中,并将索引重置为新列"svid",(请参见下面的代码和图片)

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)

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

原始df

结果df

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

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.

推荐答案

使用 reset_index 用于将索引值转换为列,并在必要时将rename列转换为

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

这篇关于如何在 pandas df中设置新索引并删除默认索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆