如何在Spark数据框中将所有列更改为double类型 [英] How to change all columns to double type in a spark dataframe
本文介绍了如何在Spark数据框中将所有列更改为double类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将spark数据帧的所有列更改为double类型,但我想知道是否有比仅循环遍历和强制转换更好的方法。
I am trying to change all the columns of a spark dataframe to double type but i want to know if there is a better way of doing it than just looping over the columns and casting.
推荐答案
使用此数据框:
df = spark.createDataFrame(
[
(1,2),
(2,3),
],
["foo","bar"]
)
df.show()
+---+---+
|foo|bar|
+---+---+
| 1| 2|
| 2| 3|
+---+---+
循环可能是最简单,更自然的解决方案。
the for
loop is problably the easiest and more natural solution.
from pyspark.sql import functions as F
for col in df.columns:
df = df.withColumn(
col,
F.col(col).cast("double")
)
df.show()
+---+---+
|foo|bar|
+---+---+
|1.0|2.0|
|2.0|3.0|
+---+---+
当然,您也可以使用python理解:
Of course, you can also use python comprehension:
df.select(
*(
F.col(col).cast("double").alias(col)
for col
in df.columns
)
).show()
+---+---+
|foo|bar|
+---+---+
|1.0|2.0|
|2.0|3.0|
+---+---+
如果列很多,第二种解决方案要好一些。
If you have a lot of columns, the second solution is a little bit better.
这篇关于如何在Spark数据框中将所有列更改为double类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文