python 3.x - Pandas insert alternate blank rows -


given following data frame:

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

i'd insert blank rows before each row. desired result is:

      b 0   nan nan 1     d 2   nan nan 3   b   nan 4   nan nan 5   c   c 6   nan nan 7   d   f 

in reality, have many rows.

thanks in advance!

use numpy , pd.dataframe

def pir(df):     nans = np.where(np.empty_like(df.values), np.nan, np.nan)     data = np.hstack([nans, df.values]).reshape(-1, df.shape[1])     return pd.dataframe(data, columns=df.columns)  pir(df1) 

enter image description here

testing , comparison

code

def banana(df):     df1 = df.set_index(np.arange(1, 2*len(df)+1, 2))     df2 = pd.dataframe(index=range(0, 2*len(df1), 2), columns=df1.columns)     return pd.concat([df1, df2]).sort_index()  def anton(df):     df = df.set_index(np.arange(1, 2*len(df)+1, 2))     return df.reindex(index=range(2*len(df)))  def pir(df):     nans = np.where(np.empty_like(df.values), np.nan, np.nan)     data = np.hstack([nans, df.values]).reshape(-1, df.shape[1])     return pd.dataframe(data, columns=df.columns) 

results

pd.concat([f(df1) f in [banana, anton, pir]],           axis=1, keys=['banana', 'anton', 'pir']) 

enter image description here

timing

enter image description here


Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -