最初,我想在两个数字(10和80)之间生成随机整数:
from random import randint
df.fillna(randint(10, 80), 'score').show()在当前列值的某一范围内生成随机小数的正确方法是什么?例如,值为25.0的'score'列的+/- 15%内的随机小数?
我研究了文档,但是只有例子显示如何用种子生成随机数。不确定在这种情况下是否合适。
发布于 2020-07-02 17:46:10
我不知道我看得对不对,但你想找出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是这里的关键功能。
发布于 2020-07-02 17:49:51
# 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)
))
)大部分的顶部是样板,但魔术发生在底部。
https://stackoverflow.com/questions/62701828
复制相似问题