使用selectExpr在pySpark中强制转换数据帧列

使用selectExpr在pySpark中强制转换数据帧列,pyspark,pyspark-dataframes,Pyspark,Pyspark Dataframes,我必须强制转换列数据类型,并且需要将一些默认值传递给数据帧中的新列。 我尝试了以下方法,但加载失败 我有一份清单: a = ["cast(col_1 as double) as col_1", "cast('DIM' as string) as new_colmn"] for items in a: select_var = items + "," select_var = select_var.strip(",") # It will remove the last unwanted

我必须强制转换列数据类型,并且需要将一些默认值传递给数据帧中的新列。 我尝试了以下方法,但加载失败

我有一份清单:

a = ["cast(col_1 as double) as col_1", "cast('DIM' as string) as new_colmn"]

for items in a:
  select_var = items + ","

select_var = select_var.strip(",")  # It will remove the last unwanted commas.
最后,我将其传递给dataframe,以强制转换旧列并创建传入变量的新列:

df2 = df1.selectExpr("*", select_var)

但是,我得到了所需的输出。这里有人能帮我吗???谢谢

您可以直接在selectExpr中传递列表,请参见下面的示例:

创建会话和示例数据帧

在类型转换之前打印架构

创建类型转换表达式

应用类型转换表达式

类型转换后打印架构

输出


谢谢,但是对于列数据类型的更改,我得到了空值<代码>“将列(列1)转换为列1”我尝试将列(列('列1')转换为双精度)转换为列1”。但这一个也有问题。请检查并让我知道??它正在使用我们传递的类型创建新列,但它不适用于dataframe中已经存在的列的类型大小写。@SureshGudimetla列1中有什么类型的值?理想情况下,它应该如上面的示例所示工作。您可以尝试打印col_1的原始值,然后键入casted values作为“cast(col_1为double)作为col_1_cast”,并调试它是否正常工作。@suresh能否提供col_1返回空值的示例数据
from pyspark.sql import SparkSession
from pyspark.sql.functions import *

spark = SparkSession.builder.getOrCreate()

sample_df = spark.createDataFrame([("123","abc")],["col_1", "col2"])
print(sample_df.schema) # Schema before Type Casting
expression = ["cast(col_1 as double) as col_1", "cast('DIM' as string) as new_colmn"]
casted_df=sample_df.selectExpr(expression)
print(casted_df.schema) # Schema after Type Casting
casted_df.show()