Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

start index at 1 for Pandas DataFrame

I need the index to start at 1 rather than 0 when writing a Pandas DataFrame to CSV.

Here's an example:

In [1]: import pandas as pd  In [2]: result = pd.DataFrame({'Count': [83, 19, 20]})  In [3]: result.to_csv('result.csv', index_label='Event_id')                                

Which produces the following output:

In [4]: !cat result.csv Event_id,Count 0,83 1,19 2,20 

But my desired output is this:

In [5]: !cat result2.csv Event_id,Count 1,83 2,19 3,20 

I realize that this could be done by adding a sequence of integers shifted by 1 as a column to my data frame, but I'm new to Pandas and I'm wondering if a cleaner way exists.

like image 394
Clark Fitzgerald Avatar asked Nov 23 '13 21:11

Clark Fitzgerald


People also ask

Do pandas start 0 or 1?

In Python pandas, start row index from 1 instead of zero without creating additional column - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.

Can you index a Pandas DataFrame?

Indexing in pandas means simply selecting particular rows and columns of data from a DataFrame. Indexing could mean selecting all the rows and some of the columns, some of the rows and all of the columns, or some of each of the rows and columns. Indexing can also be known as Subset Selection.

Is pandas 0 indexed?

column[0]][0] pandas realizes that there is no index named 0, and falls back to . iloc which locates things by array indexing. Therefore it returns what it finds at the first location of the array, which is 'example' .


2 Answers

Index is an object, and default index starts from 0:

>>> result.index Int64Index([0, 1, 2], dtype=int64) 

You can shift this index by 1 with

>>> result.index += 1  >>> result.index Int64Index([1, 2, 3], dtype=int64) 
like image 108
alko Avatar answered Sep 21 '22 08:09

alko


Just set the index before writing to CSV.

df.index = np.arange(1, len(df)) 

And then write it normally.

like image 20
TomAugspurger Avatar answered Sep 19 '22 08:09

TomAugspurger