Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 927
kshama Avatar asked Jan 18 '26 02:01

kshama


2 Answers

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

df = df.reset_index().rename(columns={'subVoyageID':'SVID'})
like image 154
jezrael Avatar answered Jan 20 '26 19:01

jezrael


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
like image 39
miradulo Avatar answered Jan 20 '26 18:01

miradulo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!