PySpark udf 中的 Numpy randint 返回意外值

时间:2021-07-12 17:06:30

标签: python dataframe numpy pyspark user-defined-functions

我创建了一个 udf 来在 PySpark 数据帧的列中生成随机的十位整数:

phone_udf = F.udf(lambda: np.random.randint(low = 1111111111, high = 9999999999), T.IntegerType())

households = sc.union([sc.parallelize([[j]
                          for j
                          in np.random.choice(household_sizes, size=partition_size, p=hh_size_probs).tolist()])
                          for i in range(partition_count)]).toDF(["_household_members"])\
               .limit(nhouseholds)\
               .withColumn("household_id", F.row_number().over(w))\
               .withColumn("_hoh_last_name_id", (F.rand() * name_count).cast("int"))\
               .withColumn("_hh_address_id", (F.rand() * address_filtered_count).cast("int"))\
               .withColumn("phone", phone_udf())

但是,生成的数据帧的“电话”列包含所有不同长度的整数,最多 10 位,包括正数和负数。我不确定为什么 np.random.randint 在 udf 中没有按预期运行。

1 个答案:

答案 0 :(得分:0)

Spark 假定为 32 位整数。由于生成的整数范围 (1111111111, 9999999999) 包含的整数太高而无法用 32 位表示,因此 spark 错误地解释了 64 位整数。使用 spark 的 LongType() 或先将整数转换为字符串都可以解决问题。