Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas how do i add an empty column after every nth column

Tags:

python

pandas

I currently have this DataFrame

col_1 col_2 col_3 col_4 col_5
   1a    2a    3a    4a    5a
   1b    2b    3b    4b    5b
   1c    2c    3c    4c    5c
   1d    2d    3d    4d    5d

I am trying to get this

col_1 col_2 NaN col_3 NaN col_4 NaN col_5 NaN
   1a    2a NaN    3a NaN   4a  NaN    5a NaN
   1b    2b NaN    3b NaN   4b  NaN    5b NaN
   1c    2c NaN    3c NaN   4c  NaN    5c NaN
   1d    2d NaN    3d NaN   4d  NaN    5d NaN

Basically from col_2 onwards, insert an empty column after every col_ How do i go about doing this? i have tried

N = len(df.columns) #
for i in range(0,N): #
    df.insert(i,'','',allow_duplicates=True)
like image 866
Benedict Ng Avatar asked Nov 30 '25 06:11

Benedict Ng


1 Answers

Try this:

[df.insert(i, '', np.nan, allow_duplicates=True) for i in range(df.shape[1], 1, -1)]

Output:

  col_1 col_2     col_3     col_4     col_5    
0    1a    2a NaN    3a NaN    4a NaN    5a NaN
1    1b    2b NaN    3b NaN    4b NaN    5b NaN
2    1c    2c NaN    3c NaN    4c NaN    5c NaN
3    1d    2d NaN    3d NaN    4d NaN    5d NaN
like image 188
Scott Boston Avatar answered Dec 01 '25 20:12

Scott Boston