如何解决PySpark:将架构应用于数据框
我有几个具有所有StringType列的DataFrame。
我想应用自定义架构-更改类型-一切正常(无错误消息)。但是在所有转换之后,我无法将count()应用于新的数据框。这就是我的工作:
my_df_1 = spark.createDataFrame(
[
("1",'foo'),("2",'bar'),],['id','txt']
)
my_df_2 = spark.createDataFrame(
[
("1",'txt']
)
#union the two DataFrames
df_union = my_df_1.unionAll(my_df_2)
#Here count still works
df_union.count()
#Create a schema
from pyspark.sql import types as T
schema = T.StructType([T.StructField('id',T.IntegerType(),True),T.StructField('txt',T.StringType(),True)])
#Convert the DataFrame to RDD and apply the schema to the DataFrame
schema_df = spark.createDataFrame(df_union.rdd,schema=schema)
#And this throws an error
schema_df.count()
#Error: TypeError: field id: IntegerType can not accept object '2' in type <class 'str'>
我哪里出错了?
解决方法
创建数据框时,Id是字符串类型。您不能像这样将字符串更改为整数。 如果需要更改列的类型,可以在列级别使用cast('int')
,只需 cast
id列,如下所示。
df_union = df_union.withColumn("id",F.col("id").cast(T.IntegerType()))
schema_df = spark.createDataFrame(df_union.rdd,schema=df_union.schema)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。