我有一个数据框,其中包含几列(1000)并且它们具有字符串类型。我想将它们转换为一次浮动不是一列一列而是所有数据帧。
我知道这个存在
from pyspark.sql.types import IntegerType
data_df = data_df.withColumn("column_name", data_df["columns_name"].cast(IntegerType()))
但我正在研究这样的事情:
data_df = data_df.cast(IntegerType()))
这是退出是因为我在互联网上做了一些研究,但我什么也没找到
答案 0 :(得分:1)
我想说您最好的选择是将所有列预先选择到一个列表中,然后通过在选择中进行强制转换来编写列表理解。
from pyspark.sql.types import IntegerType, FloatType
import pyspark.sql.functions as f
cols = df.columns
df.select(
*[f.col(col).cast(IntegerType()).alias(col) for col in cols]
)
# for casting to float please replace with FloatType()
但是,请注意 pyspark
会在 cast
上静默失败,例如如果列的一行无法转换为目标类型。这意味着如果您的 NULL
列无法转换为 StringType
,整个列将返回 IntegerType
。
因此,我建议您运行一些数据验证测试来检查您的数据框是否按预期填充。 great_expectations
之类的工具非常适合这一点。