'Adding empty rows in Pandas dataframe

I'd like to append consistently empty rows in my dataframe. I have following code what does what I want but I'm struggling in adjusting it to my needs:

s = pd.Series('', data_only_trades.columns)
f = lambda d: d.append(s, ignore_index=True)

set_rows = np.arange(len(data_only_trades)) // 4
empty_rows = data_only_trades.groupby(set_rows, group_keys=False).apply(f).reset_index(drop=True)
  • How can I adjust the code so I add two or more rows instead of one?
  • How can I set a starting point (e.g. it should start with row 5 -- Do I have to use .loc then in arange?)

Also tried this code but I was struggling in setting the starting row and the values to blank (I got NaN):

df_new = pd.DataFrame() 
for i, row in data_only_trades.iterrows():
   df_new = df_new.append(row)
for _ in range(2):
   df_new = df_new.append(pd.Series(), ignore_index=True)

Thank you!



Solution 1:[1]

import numpy as np
v = np.ndarray(shape=(numberOfRowsYouWant,df.values.shape[1]), dtype=object)
v[:] = ""
pd.DataFrame(np.vstack((df.values, v)))

I think you can use NumPy but, if you want to use your manner, simply convert NaN to "":

df.fillna("")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MoRe