Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas insert alternate blank rows

Given the following data frame:

import pandas as pd
import numpy as np
df1=pd.DataFrame({'A':['a','b','c','d'],
                 'B':['d',np.nan,'c','f']})
df1
    A   B
0   a   d
1   b   NaN
2   c   c
3   d   f

I'd like to insert blank rows before each row. The desired result is:

    A   B
0   NaN NaN
1   a   d
2   NaN NaN
3   b   NaN
4   NaN NaN
5   c   c
6   NaN NaN
7   d   f

In reality, I have many rows.

Thanks in advance!

like image 212
Dance Party Avatar asked Aug 24 '16 04:08

Dance Party


People also ask

How do you insert an alternate blank row?

Select the cells where the empty rows need to appear and press Shift + Space. When you pick the correct number of rows, right-click within the selection and choose the Insert option from the menu list.

How do you add blank rows in pandas?

Empty rows can be appended by using the df. loc[df. shape[0]] and assigning None values for all the existing columns. For example, if your dataframe has three columns, you can create a series with 3 None values and assign it at the last position of the dataframe.

How do I add a blank column in pandas?

There are multiple ways to add a new empty/blank column (single or multiple columns) to a pandas DataFrame by using assign operator, assign() , insert() and apply() methods. By using these you can add one or multiple empty columns with either NaN , None , Blank or Empty string values to all cells.


1 Answers

I think you could change your index like @bananafish did and then use reindex:

df1.index = range(1, 2*len(df1)+1, 2)
df2 = df1.reindex(index=range(2*len(df1)))

In [29]: df2
Out[29]:
     A    B
0  NaN  NaN
1    a    d
2  NaN  NaN
3    b  NaN
4  NaN  NaN
5    c    c
6  NaN  NaN
7    d    f
like image 168
Anton Protopopov Avatar answered Nov 15 '22 09:11

Anton Protopopov