7

Suppose have following data frame

        A   B   
1   2   3   4   5
4   5   6   7   8

I want to check if df(0,0) is nan then insert pd.series(np.nan) at 0th position. So in above case it will be

        A   B   

1   2   3   4   5
4   5   6   7   8

I am able to check (0,0) element but how do I insert empty row at first position?

2
  • care to explain down vote guys? Commented Jul 2, 2018 at 12:41
  • 1
    I think it is a good question, this thread contains the only answer I found to a simple question I was looking for: append the last row: df.loc[len(df)] = np.NaN. Ok for me.
    – jaromrax
    Commented Sep 22, 2020 at 12:36

2 Answers 2

14

EDIT:

For last pandas version use concat:

df = pd.DataFrame(np.arange(1, 9).reshape(2, -1), columns=list('ABCD'))
print (df)
   A  B  C  D
0  1  2  3  4
1  5  6  7  8

df1 = pd.DataFrame([[np.nan] * len(df.columns)], columns=df.columns)
df = pd.concat([df1, df], ignore_index=True)
print (df)
     A    B    C    D
0  NaN  NaN  NaN  NaN
1  1.0  2.0  3.0  4.0
2  5.0  6.0  7.0  8.0

Old pandas versions:

Use append of DataFrame with one empty row:

df1 = pd.DataFrame([[np.nan] * len(df.columns)], columns=df.columns)
df = df1.append(df, ignore_index=True)
print (df)

     A    B    C    D    E
0  NaN  NaN  NaN  NaN  NaN
1  1.0  2.0  3.0  4.0  5.0
2  4.0  5.0  6.0  7.0  8.0
5
  • Where are you checking, (0,0) index is nan? Commented Jul 2, 2018 at 13:09
  • How come it got 3 more column? and why A and B shifted? sorry but got confuse. Commented Jul 2, 2018 at 13:10
  • 1
    @PiyushS.Wanare - sorry, what is print (df.head().to_dict()) of sample?
    – jezrael
    Commented Jul 2, 2018 at 13:11
  • for more recent visitors to this q&a, pandas >= 2 has no attribute 'append' so won't work
    – antonymott
    Commented Jun 29 at 13:46
  • 1
    @antonymott - thank you, added new solution.
    – jezrael
    Commented Jul 1 at 5:42
7

Perhaps you can first append a row with zeros, shift the whole rows and overwrite the first with 0:

df
   A  B  C  D  E
0  1  2  3  4  5
1  4  5  6  7  8

df.loc[len(df)] = 0

df
   A  B  C  D  E
0  1  2  3  4  5
1  4  5  6  7  8
2  0  0  0  0  0

df = df.shift()

df.loc[0] = 0

df
     A    B    C    D    E
0  0.0  0.0  0.0  0.0  0.0
1  1.0  2.0  3.0  4.0  5.0
2  4.0  5.0  6.0  7.0  8.0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.