Tobias To
Tobias To

Reputation: 25

How to update the Index of df with a new Index?

I am currently having one df which has an incomplete Index. like this:

Idx  bar  baz  zoo
001   A    1    x
003   B    2    y
005   C    3    z
007   A    4    q
008   B    5    w
009   C    6    t

I have the complete Index([001, 002, ...... 010]). Would like to how to supplement the complete Index into the incomplete df.

Idx  bar  baz  zoo
001   A    1    x
002  nan  nan  nan
003   B    2    y
004  nan  nan  nan
005   C    3    z
006  nan  nan  nan
007   A    4    q
008   B    5    w
009   C    6    t 
010  nan  nan  nan

The nan can be "", the purpose is for me to identify which case I am currently missing. It's the first time I ask question on stackover, apology for the poor formatting.

Upvotes: 0

Views: 96

Answers (2)

Derek Eden
Derek Eden

Reputation: 4638

you can do this easily by using the pandas df reindex method..

df.reindex

all you have to do is supply a list to be used as the new index i.e.

full_index = ['001','002','003','004','005','006','007','008','009','010']  

then pass this into the reindex method like this:

df = df.reindex(full_index)

the method will automatically put nan values into the rows with indices that were not in the original index...

e.g.:

df = pd.DataFrame({'bar':['A','B','C','A','B','C'],'baz':[1,2,3,4,5,6],'zoo':['x','y','z','q','w','t']}, index = ['001','003','005','007','008','009']) #your original df
full_index = ['001','002','003','004','005','006','007','008','009','010']  
df = df.reindex(full_index)

output:

     bar  baz  zoo
001    A  1.0    x
002  NaN  NaN  NaN
003    B  2.0    y
004  NaN  NaN  NaN
005    C  3.0    z
006  NaN  NaN  NaN
007    A  4.0    q
008    B  5.0    w
009    C  6.0    t
010  NaN  NaN  NaN

Upvotes: 2

BENY
BENY

Reputation: 323376

You can try with reindex

df=df.reindex(completeIndex)

Upvotes: 2

Related Questions