0

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.

Tobias To
  • 25
  • 1
  • 4
  • 2
    Possible duplicate of [Append an empty row in dataframe using pandas](https://stackoverflow.com/questions/39998262/append-an-empty-row-in-dataframe-using-pandas) – Henry Woody Nov 12 '19 at 02:49
  • This method works, I need to use a for-loop though: ``` # setup a complete DF with complete index for index in index_li: if index not in df.index: df= df.append(pd.Series(name=index)) ``` – Tobias To Nov 12 '19 at 03:22

2 Answers2

2

You can try with reindex

df=df.reindex(completeIndex)
BENY
  • 317,841
  • 20
  • 164
  • 234
2

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
Derek Eden
  • 4,403
  • 3
  • 18
  • 31