PolarBear10
PolarBear10

Reputation: 2305

Add a row with random numbers every n amount of rows in pandas

This is my DataFrame.

A | B | C | D
0   4   8   9
1   5   8   9
2   6   8   9
3   7   8   9

I would like to add a row every second row with a random number, so it will look like that.

A | B | C | D
0   4   8   9
1   5   8   9
596 596 596 596
2   6   8   9
3   7   8   9
123 123 123 123

The following code from another question thanks to PiR square, add zero to every 2nd row. How can I modify it to add a random number every second row OR an increment of the previous random number, such as.

A | B | C | D
a   a   a   a
b   b   b   b
0   0   0   0
c   c   c   c
d   d   d   d
1   1   1   1

Here you can see, that it starts with 0 then increments to 1 on the next second row

This code adds zero to every second row from the other StackOverflow question

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

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

Upvotes: 1

Views: 369

Answers (1)

Space Impact
Space Impact

Reputation: 13255

Change your lambda function as, Change the range as per your requirement in randint:

f = lambda d: d.append(pd.Series(np.random.randint(0,1000,size=1).repeat(4), df.columns), ignore_index=True)

or:

f = lambda d: d.append(pd.Series(np.random.randint(0,1000,size=1).tolist()[0], df.columns), ignore_index=True)

Upvotes: 2

Related Questions