Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reindexing a pandas DataFrame using a dict (python3)

Is there a way, without use of loops, to reindex a DataFrame using a dict? Here is an example:

df = pd.DataFrame([[1,2], [3,4]])
dic = {0:'first', 1:'second'}

I want to apply something efficient to df for obtaining:

        0  1
first   1  2
second  3  4

Speed is important, as the index in the actual DataFrame I am dealing with has a huge number of unique values. Thanks

like image 374
splinter Avatar asked Mar 16 '17 15:03

splinter


1 Answers

You need the rename function:

df.rename(index=dic)

#       0   1
#first  1   2
#second 3   4

Modified the dic to get the results: dic = {0:'first', 1:'second'}

like image 125
Psidom Avatar answered Sep 21 '22 10:09

Psidom