如何为每一行生成一个随机数?

2024-10-16 17:14:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手,非常感谢您的帮助

我有一个包含2000行和2列的数据框:Row和Pct。 基本上,我想创建第三列,它将基于以下逻辑:

  1. 要为第一行生成一个随机数(介于0到1之间),我们将这个数字称为X
  2. 如果X>;Pct我想在新列中添加1,并为第一行生成一个额外的随机数,然后再次检查X是否>;Pct和if so-在新列中添加1并生成额外的随机数,依此类推
  3. 如果X<=Pct我想在新列中添加1,然后移到下一行,依此类推

希望我能解释清楚:)

谢谢

编辑: 关于您的问题:

  1. 这只是一个例子,我上传了带有CSV文件的df
  2. 添加1->;这意味着新列基本上是空的(零),如果条件为真,我想在正确的行中添加1。基本上,它应该充当计数器
data = {
        'Pct': [0.8,0.4,0.3,0.7,0.3,1,0.23,0.75,0.93,0.6],
        'Row': [1,2,3,4,5,6,7,8,9,10]
}
df = pd.DataFrame(data, columns = ['Row','Pct'])
df

    Row Pct
0   1   0.80
1   2   0.40
2   3   0.30
3   4   0.70
4   5   0.30
5   6   1.00
6   7   0.23
7   8   0.75
8   9   0.93
9   10  0.60

Tags: csv数据ltgt编辑dfdataif
1条回答
网友
1楼 · 发布于 2024-10-16 17:14:55

您可以这样做:

def generate_random_values(row):
    pct_value = float(row['Pct'])
    # 1 . Generate random no bw 0 and 1
    x = np.random.random()
    # 2. Init value of new column
    new_col = 0
    # 3. while x > pct_value, add 1 to new_col and generate new random no
    while x > pct_value:
        new_col += 1
        x = np.random.random()
    # 4. Here x < = pct_value, add 1 to new col and return for the current row
    new_col += 1
    return new_col

然后:

df['new_column'] = df.apply(func=generate_random_values, axis=1)
print (df)
>>>
   Row   Pct  new_column
0    1  0.80           1
1    2  0.40           2
2    3  0.30           1
3    4  0.70           1
4    5  0.30           8
5    6  1.00           1
6    7  0.23           1
7    8  0.75           1
8    9  0.93           1
9   10  0.60           2

在运行上述函数之前检查“Pct”列的最小阈值也是一个好主意,因为您不想运行到无限循环中

相关问题 更多 >