Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel to Pandas DataFrame using first column as index

Tags:

python

pandas

I have a very simple table in Excel that I'm trying to read into a DataFrame

Excel data

Code:

from pandas import DataFrame, Series
import pandas as pd

df = pd.read_excel('params.xlsx', header=[0,1], index_col=None)

This results in the following DataFrame:

DataFrame

I didn't expect param1.key to become the index, especially after having set index_col=None. Is there a way to get the data into a DataFrame with a generated index instead of the data from the first column?

Update — here's what happens when you try reset_index() to resolve the issue:

DataFrame after reset_index()

Version info:

  • Python 3.5.0
  • pandas (0.17.1)
  • xlrd (0.9.4)
like image 478
DocZerø Avatar asked Dec 01 '15 12:12

DocZerø


People also ask

How do I make the first column an index in Excel?

An index column is also added to an Excel worksheet when you load it. To open a query, locate one previously loaded from the Power Query Editor, select a cell in the data, and then select Query > Edit. For more information see Create, load, or edit a query in Excel (Power Query). Select Add Column > Index Column.

How do I make the first column an index in Python?

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 set a column as index in a DataFrame?

We can set a specific column or multiple columns as an index in pandas DataFrame. Create a list of column labels to be used to set an index. We need to pass the column or list of column labels as input to the DataFrame. set_index() function to set it as an index of DataFrame.


1 Answers

It seems like a bug. You can get a column out of your index by simply doing:

df['columnName'] = df.index
like image 95
Blue Moon Avatar answered Oct 20 '22 00:10

Blue Moon