Search code examples
pythonpandas

Pandas insert empty row at 0th position


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?


Solution

  • 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