kshama
kshama

Reputation: 49

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

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.

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

Original df

orig df

Resultant df

new 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.

Upvotes: 3

Views: 11708

Answers (2)

miradulo
miradulo

Reputation: 29740

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

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

Upvotes: 1

jezrael
jezrael

Reputation: 863711

Use reset_index for convert index values to column and if necessary rename column:

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

Upvotes: 5

Related Questions