Vachan Bhat Vachan Bhat - 6 months ago 2081
Python Question

How to remove index from a created Dataframe in Python?

I have created a Dataframe

df
by merging 2 lists using the following command:

import pandas as pd
df=pd.DataFrame({'Name' : list1,'Probability' : list2})


But I'd like to remove the first column (The index column) and make the column called
Name
the first column. I tried using
del df['index']
and
index_col=0
. But they didn't work. I also checked
reset_index()
and that is not what I need. I would like to completely remove the whole index column from a Dataframe that has been created like this (As mentioned above). Someone please help!

Answer

You can use set_index, docs:

import pandas as pd

list1 = [1,2]
list2 = [2,5]
df=pd.DataFrame({'Name' : list1,'Probability' : list2})
print (df)
   Name  Probability
0     1            2
1     2            5

df.set_index('Name', inplace=True)
print (df)
      Probability
Name             
1               2
2               5

If you need also remove index name:

df.set_index('Name', inplace=True)
#pandas 0.18.0 and higher
df = df.rename_axis(None)
#pandas bellow 0.18.0
#df.index.name = None
print (df)
   Probability
1            2
2            5