Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set an unnamed column as the index?

In all the examples I have found, a column name is usually required to set it as the index

Instead of going into excel to add a column header, I was wondering if it's possible to set an empty header as the index. The column has all the values I want included, but lacks a column name:

enter image description here

My script is currently:

import pandas as pd
data = pd.read_csv('file.csv')
data
like image 708
DanONS Avatar asked Sep 01 '17 11:09

DanONS


People also ask

How do you set a column as index?

To create an index, from a column, in Pandas dataframe you use the set_index() method. For example, if you want the column “Year” to be index you type <code>df. set_index(“Year”)</code>. Now, the set_index() method will return the modified dataframe as a result.

How do you give a column an index name?

Assign Column as Index using set_index() DataFrame. set_index() method to set a column as an index. In the below example, I am setting the column Courses as Index. When you do this, the column name is assigned as an index name and it will be removed from columns.

What is unnamed column in pandas?

An unnamed column in pandas comes when you are reading the CSV file using it. Sometimes we require to drop columns in the dataset that we are not required. It not only saves memory but is also helpful in analyzing the data efficiently.

How do I rename an unnamed zero column?

rename( columns={0 :'new column name'}, inplace=True ) . There is no need to use 'Unnamed: 0' , simply use the column number, which is 0 in this case and then supply the 'new column name' .


3 Answers

You could also just select the column by id with iloc:

data = data.set_index(data.iloc[:, 0])

Or when you call pd.read_csv(), specify index_col:

data = pd.read_csv('path.csv', index_col=0)
like image 168
Kyle Avatar answered Nov 11 '22 19:11

Kyle


You don't need to rename the first column in excel. It's as easy in pandas as well:

new_columns = data.columns.values
new_columns[0] = 'Month'
data.columns = new_columns

Afterwards, you can set the index:

data = data.set_index('Month')
like image 29
StefanK Avatar answered Nov 11 '22 18:11

StefanK


You can do as follows:

import pandas as pd
data = pd.read_csv('file.csv',index_col=0)
data
like image 29
Kirti Nikam Avatar answered Nov 11 '22 17:11

Kirti Nikam