23

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!

3 Answers 3

48

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
Sign up to request clarification or add additional context in comments.

3 Comments

There is an insane algorithm that I'm working on. I have used up all my brain cells on it in the last 2 days haha. I'll ask for help if I can't figure it out by tonight.
I can try it or maybe someone else. I hope you found solution. Good luck!
@jezrael This serves the purpose but the id is misplaced in the row. Any fix for that ?
8

If you want to save your dataframe to a spreadsheet for a report.. it is possible to format the dataframe to eliminate the index column using xlsxwriter.

writer = pd.ExcelWriter("Probability" + ".xlsx", engine='xlsxwriter')

df.to_excel(writer, sheet_name='Probability', startrow=3, startcol=0, index=False)

writer.save()

index=False will then save your dataframe without the index column.

I use this all the time when building reports from my dataframes.

Comments

-2

I think the best way is to hide the index using the hide_index method

df = df.style.hide_index()

this will hide the index from the dataframe.

4 Comments

Did you check this Somesh? On my system this method returns a pandas.io.formats.style.Styler object, not a DataFrame
@user1330734 it works, I have tested it with my dataset. can you post your error here? it seems from you error the object you are trying to convert is not a dataframe.
>>> type(df) <class 'pandas.core.frame.DataFrame'> >>> df2 = df.style.hide_index() >>> type(df2) <class 'pandas.io.formats.style.Styler'>
This solution has to install Jinja2. That raise this error: Missing optional dependency 'Jinja2'. DataFrame.style requires jinja2. Use pip or conda to install Jinja2.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.