如何传递模式以从现有Dataframe创建新的Dataframe?

Bla*_*ard 4 python python-3.x apache-spark pyspark

要将模式传递给json文件,我们这样做:

from pyspark.sql.types import (StructField, StringType, StructType, IntegerType)
data_schema = [StructField('age', IntegerType(), True), StructField('name', StringType(), True)]
final_struc = StructType(fields = data_schema)
df =spark.read.json('people.json', schema=final_struc)
Run Code Online (Sandbox Code Playgroud)

上面的代码按预期工作.但是现在,我在表格中有数据显示:

df = sqlContext.sql("SELECT * FROM people_json")               
Run Code Online (Sandbox Code Playgroud)

但是如果我尝试使用以下命令将新模式传递给它,则它不起作用.

df2 = spark.sql("SELECT * FROM people_json", schema=final_struc)
Run Code Online (Sandbox Code Playgroud)

它给出以下错误:

sql()得到了一个意外的关键字参数'schema'

注意:我正在使用Databrics Community Edition

  • 我错过了什么?
  • 如果表中有数据而不是某些JSON文件,如何传递新模式?

Sha*_*ala 6

您无法将新架构应用于已创建的数据帧.但是,您可以通过转换为另一种数据类型来更改每个列的架构,如下所示.

df.withColumn("column_name", $"column_name".cast("new_datatype"))
Run Code Online (Sandbox Code Playgroud)

如果需要应用新架构,则需要转换为RDD并再次创建新数据帧,如下所示

df = sqlContext.sql("SELECT * FROM people_json")
val newDF = spark.createDataFrame(df.rdd, schema=schema)
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!