gpt4 book ai didi

python - 如何将 PySpark 数据帧的每个非字符串列与浮点常量相除或相乘?

转载 作者:行者123 更新时间:2023-12-03 12:14:00 24 4
gpt4 key购买 nike

我的输入数据框如下所示

from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("Basics").getOrCreate()

df=spark.createDataFrame(data=[('Alice',4.300,None),('Bob',float('nan'),897)],schema=['name','High','Low'])

+-----+----+----+
| name|High| Low|
+-----+----+----+
|Alice| 4.3|null|
| Bob| NaN| 897|
+-----+----+----+

除以 10.0 时的预期输出
+-----+----+----+
| name|High| Low|
+-----+----+----+
|Alice| 0.43|null|
| Bob| NaN| 89.7|
+-----+----+----+

最佳答案

我不知道任何可以做到这一点的库函数,但这个片段似乎做得很好:

CONSTANT = 10.0

for field in df.schema.fields:
if str(field.dataType) in ['DoubleType', 'FloatType', 'LongType', 'IntegerType', 'DecimalType']:
name = str(field.name)
df = df.withColumn(name, col(name)/CONSTANT)


df.show()

输出:
+-----+----+----+
| name|High| Low|
+-----+----+----+
|Alice|0.43|null|
| Bob| NaN|89.7|
+-----+----+----+

关于python - 如何将 PySpark 数据帧的每个非字符串列与浮点常量相除或相乘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44807818/

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