【问题标题】:Pyspark - how to generate random numbers within a certain range of a column value?Pyspark - 如何在列值的某个范围内生成随机数?
【发布时间】:2020-10-23 09:02:11
【问题描述】:

最初我想在两个数字(10 和 80)之间生成随机整数:

from random import randint
df.fillna(randint(10, 80), 'score').show()

在当前列值的特定范围内生成随机小数的正确方法是什么?例如,'score' 列的 +/- 15% 内的随机小数,值为 25.0?

我查看了documentation,但只有一些示例展示了如何使用种子生成随机数。不确定它是否适合这种情况。

【问题讨论】:

  • 除以 100 或 10
  • 导入随机数 >>> random_decimal = random.randint(100, 1000)/100 >>> print(random_decimal)

标签: python python-3.x dataframe random pyspark


【解决方案1】:

我不确定我的阅读是否正确,但您希望找到介于 21.25 和 28.75 之间的随机浮点数范围?如果是这样:

score = 25.0
left_most_column =  score - (score*0.15) #21.25
right_most_column =  score + (score*0.15) #28.75
answer = random.uniform(left_most_column, right_most_column)

Uniform是这里的关键函数。

【讨论】:

    【解决方案2】:
    # Imports
    from random import choice, randint
    
    from pyspark.sql import functions as F
    from pyspark.sql import SQLContext
    from pyspark.sql.types import IntegerType, StructField, StructType
    
    # Variable setup
    rand_range = 0.15
    schema = StructType(
        [
            StructField("score", IntegerType(), nullable=False),
            StructField("random_score", IntegerType(), nullable=True),
        ]
    )
    data = list()
    
    # Create the score column data
    for i in range(0, 50):
        data.append(
            {
                "score": randint(10, 80),
            }
        )
    
    # Create the Spark dataframe
    df = SQLContext.createDataFrame(data, schema)
    
    # Generate the randomized score column
    df = df.withColumn(
        "random_score",
        F.col("score") +
        (choice([-1, 1]) *
         randint(
             F.col("score") * (1 - rand_range), 
             F.col("score") * (1 + rand_range)
         ))
    )
    

    大部分顶部是样板,但神奇发生在底部。

    1. 拿分数列
    2. 在该值的 +/- 15% 之间创建一个随机数
    3. 乘以随机的 +/- 1 得到加法或减法。

    【讨论】:

    • 原始问题要求小数,在这种情况下,您需要更改 random_score 类型为 FloatType
    猜你喜欢
    • 2015-06-02
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2018-04-08
    • 1970-01-01
    • 2010-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多