1

So far, I have this code that adds a row of zeros every other row (from this question):

import pandas as pd
import numpy as np

def Add_Zeros(df):

    zeros = np.where(np.empty_like(df.values), 0, 0)
    data = np.hstack([df.values, zeros]).reshape(-1, df.shape[1])
    df_ordered = pd.DataFrame(data, columns=df.columns)

    return df_ordered

Which results in the following data frame:

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

But I need it to add the row of zeros every 2nd row instead, like this:

    A   B
0   a   a
1   b   b
2   0   0
3   c   c
4   d   d
5   0   0

I've tried altering the code, but each time, I get an error that says that zeros and df don't match in size.

I should also point out that I have a lot more rows and columns than I wrote here.

How can I do this?

warqgui
  • 21
  • 1
  • 5

1 Answers1

2

Option 1
Using groupby

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

grp = np.arange(len(df)) // 2
df.groupby(grp, group_keys=False).apply(f).reset_index(drop=True)

   A  B
0  a  a
1  b  b
2  0  0
3  c  c
4  d  d
5  0  0

Option 2

from itertools import repeat, chain

v = df.values

pd.DataFrame(
    np.row_stack(list(chain(*zip(v[0::2], v[1::2], repeat(z))))),
    columns=df.columns
)

   A  B
0  a  a
1  b  b
2  0  0
3  c  c
4  d  d
5  0  0
piRSquared
  • 285,575
  • 57
  • 475
  • 624