Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increase index of pandas DataFrame by one

Tags:

python

pandas

I'd like to have my dataframe start with index 1 instead of 0. But somehow I am not getting it:

In[1]: df = pd.DataFrame([[4,7],[10,11],[7,2]],columns=['one', 'two'])
In[2]: df
Out[2]: 
   one  two
0    4    7
1   10   11
2    7    2
In[3]: df.reindex(range(1,len(df)+1))
Out[3]: 
   one  two
1   10   11
2    7    2
3  NaN  NaN

Where did my first row go? What am I getting wrong about reindex()?

like image 367
Toby Avatar asked May 15 '15 20:05

Toby


People also ask

How do I change the index of a pandas DataFrame?

To change the index values we need to use the set_index method which is available in pandas allows specifying the indexes. where, inplace parameter accepts True or False, which specifies that change in index is permanent or temporary. True indicates that change is Permanent.

What does set_index do in pandas?

Pandas set_index() is a method to set a List, Series or Data frame as index of a Data Frame. Index column can be set while making a data frame too. But sometimes a data frame is made out of two or more data frames and hence later index can be changed using this method.


2 Answers

The reindexing does not reassign the index values and preserve the order for that you can assign directly:

In [25]:

df.index = range(1,len(df)+1)
df
Out[25]:
   one  two
1    4    7
2   10   11
3    7    2

The docs show that you are conforming your data to the new index which will introduce NaN values where none existed hence why you lost a row, this is why there is a fillna param for reindex.

like image 58
EdChum Avatar answered Oct 04 '22 01:10

EdChum


To increase your index with 1 you can simply modify the index like this, df.index += 1.

Full example:

In [1]: import pandas as pd

In [2]: df = pd.DataFrame([[4,7],[10,11],[7,2]],columns=['one', 'two'])

In [3]: df
Out[3]:
   one  two
0    4    7
1   10   11
2    7    2

In [4]: df.index += 1

In [5]: df
Out[5]:
   one  two
1    4    7
2   10   11
3    7    2
like image 20
joctee Avatar answered Oct 04 '22 02:10

joctee