gpt4 book ai didi

python - pandas 中每 n 行添加一行随机数

转载 作者:行者123 更新时间:2023-12-01 01:26:27 25 4
gpt4 key购买 nike

这是我的数据框。

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

我想每隔一行添加一个随机数,所以它看起来像这样。

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

以下代码来自另一个问题,感谢 PiR square,向每第二行添加零。我如何修改它以每隔两行添加一个随机数或前一个随机数的增量,例如。

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

在这里您可以看到,它从 0 开始,然后在接下来的第二行增加到 1

此代码向其他 StackOverflow 问题的每隔一行添加零

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)

最佳答案

将 lambda 函数更改为,根据 randint 中的要求更改范围:

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

或者:

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

关于python - pandas 中每 n 行添加一行随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53301892/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com