Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing index column in pandas when reading a csv

Tags:

python

pandas

I have the following code which imports a CSV file. There are 3 columns and I want to set the first two of them to variables. When I set the second column to the variable "efficiency" the index column is also tacked on. How can I get rid of the index column?

df = pd.DataFrame.from_csv('Efficiency_Data.csv', header=0, parse_dates=False) energy = df.index efficiency = df.Efficiency print efficiency 

I tried using

del df['index'] 

after I set

energy = df.index 

which I found in another post but that results in "KeyError: 'index' "

like image 229
Bogdan Janiszewski Avatar asked Nov 20 '13 21:11

Bogdan Janiszewski


People also ask

How do I save a pandas DataFrame to CSV without index?

pandas DataFrame to CSV with no index can be done by using index=False param of to_csv() method. With this, you can specify ignore index while writing/exporting DataFrame to CSV file.

How do you delete an index column in Python?

We can remove the index column in existing dataframe by using reset_index() function. This function will reset the index and assign the index columns start with 0 to n-1. where n is the number of rows in the dataframe.


1 Answers

When writing to and reading from a CSV file include the argument index=False and index_col=False, respectively. Follows an example:

To write:

 df.to_csv(filename, index=False) 

and to read from the csv

df.read_csv(filename, index_col=False)   

This should prevent the issue so you don't need to fix it later.

like image 154
Steve Avatar answered Oct 06 '22 01:10

Steve