Reputation: 215
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:
My script is currently:
import pandas as pd
data = pd.read_csv('file.csv')
data
Upvotes: 11
Views: 15919
Reputation: 2206
You can do as follows:
import pandas as pd
data = pd.read_csv('file.csv',index_col=0)
data
Upvotes: 3
Reputation: 2894
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)
Upvotes: 16
Reputation: 61
When I have encountered columns missing names, Pandas always name them 'Unnamed: n', where n = ColumnNumber-1. ie 'Unnamed: 0' for first column, 'Unnamed: 1' for second etc. So I think that in your case the following code should be useful:
# set your column as the dataframe index
data.index = data['Unnamed: 0']
# now delete the column
data.drop('Unnamed: 0', axis=1, inplace=True)
# also delete the index name which was 'Unnamed: 0' obviously
del data.index.name
Upvotes: 0
Reputation: 2180
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')
Upvotes: 7