Search code examples
pythonpandasdataframeindexingrow

Insert an empty row at a specific index and shift its values down dataframe


so for example I have this dataframe:

onset length
1 2.215 1.3
2 23.107 1.3
3 41.815 1.3
4 61.606 1.3
5 Nan Nan

and want to change it to this :

onset length
1 2.215 1.3
2 Nan Nan
3 23.107 1.3
4 41.815 1.3
5 61.606 1.3

Solution

  • You can stack appends if necessary.

    i = 2 # your target index
    
    head = df[:i]
    tail = df[i:]
    
    inserted = pd.DataFrame([[np.nan] * len(df.columns)], columns=df.columns)
    
    result = head.append(inserted, ignore_index=True)
    result = result.append(tail, ignore_index=True)
    
    print(result)