Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 388
controlfreak Avatar asked May 20 '16 16:05

controlfreak


People also ask

How do you remove a set index from a data frame?

Use DataFrame.reset_index() function We can use DataFrame. reset_index() to reset the index of the updated DataFrame. By default, it adds the current row index as a new column called 'index' in DataFrame, and it will create a new row index as a range of numbers starting at 0.

How do I remove the index and header from a data frame?

Just simply put header=False and for eliminating the index using index=False.

How do I drop index rows in pandas?

To drop rows based on certain conditions, select the index of the rows which pass the specific condition and pass that index to the drop() method. In this code, (df['Unit_Price'] >400) & (df['Unit_Price'] < 600) is the condition to drop the rows.


1 Answers

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
like image 118
jezrael Avatar answered Sep 28 '22 02:09

jezrael