将RDD转为DataFrame的方式有:

1. 将RDD转换为Row,之后创建dataframe

rdd = stringCSVRDD.map(lambda p: Row(id=p[0], name=p[1], age=p[2], eyeColor=p[3]))
df = spark.createDataFrame(rdd)

通过该方式创建dataframe,书写简单,字段类型通过前100条数据类型进行自动推断。

若字段类型不能推断出,则会报异常:

ValueError: Some of types cannot be determined by the first 100 rows, please try again with sampling

异常:Some of types cannot be determined by the first 100 rows, please try again with sampling

此时,需使用第二种方式进行dataframe的创建,指定字段的类型

2. 通过定义schema形式

schema = StructType(
    [StructField('id', LongType(), True), StructField('name', StringType(), True), StructField('age', LongType(), True),
     StructField('eyeColor', StringType(), True)])
# Apply the schema to the RDD and Create DataFrame
df = spark.createDataFrame(stringCSVRDD, schema)

 

相关文章:

  • 2022-12-23
  • 2021-11-20
  • 2021-10-01
  • 2021-07-12
  • 2021-10-26
  • 2021-08-28
  • 2022-01-16
猜你喜欢
  • 2022-12-23
  • 2021-10-20
  • 2022-12-23
  • 2021-08-06
  • 2021-11-26
  • 2021-06-16
  • 2021-09-22
相关资源
相似解决方案