Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
522 views
in Technique[技术] by (71.8m points)

python - Pandas: Inserting an empty row after every 2nd row in a data frame

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...