Python 将dataframe附加到DataRicks中的现有表

Python 将dataframe附加到DataRicks中的现有表,python,pandas,apache-spark,pyspark,databricks,Python,Pandas,Apache Spark,Pyspark,Databricks,我想在DataRicks(12列)中的现有表中附加一个pandas dataframe(8列),并用None值填充其他4列。以下是我尝试过的: spark_df = spark.createDataFrame(df) spark_df.write.mode("append").insertInto("my_table") 它抛出了错误: ParseException:“\nmismatched input':”应为(第1行,位置4)\n\n==SQL==my\u表 看起来spark无法用不匹配

我想在DataRicks(12列)中的现有表中附加一个pandas dataframe(8列),并用None值填充其他4列。以下是我尝试过的:

spark_df = spark.createDataFrame(df)
spark_df.write.mode("append").insertInto("my_table")
它抛出了错误:

ParseException:“\nmismatched input':”应为(第1行,位置4)\n\n==SQL==my\u表


看起来spark无法用不匹配的列处理此操作,有什么方法可以实现我想要的吗?

我认为最自然的做法是使用select()转换将缺少的列添加到8列数据帧,然后使用unionAll()转换将两者合并

from pyspark.sql import Row
from pyspark.sql.functions import lit

bigrow = Row(a='foo', b='bar')
bigdf = spark.createDataFrame([bigrow])
smallrow = Row(a='foobar')
smalldf = spark.createDataFrame([smallrow])

fitdf = smalldf.select(smalldf.a, lit(None).alias('b'))

uniondf = bigdf.unionAll(fitdf)
你能试试这个吗

df = spark.createDataFrame(pandas_df)

df_table_struct = sqlContext.sql('select * from my_table limit 0')

for col in set(df_table_struct.columns) - set(df.columns):
    df = df.withColumn(col, F.lit(None))

df_table_struct = df_table_struct.unionByName(df)

df_table_struct.write.saveAsTable('my_table', mode='append')

感谢您的回答,您能提供一个示例代码吗?我不熟悉spark操作。谢谢,但我想保留该表并将其附加到该表中,它看起来每次都会有一个新的uniondf。我理解。但是spark数据帧是不可变的:只能创建新的副本。我仍然会遇到相同的错误:”调用o6690.insertInto时出错:org.apache.spark.sql.catalyst.parser.ParseException:输入不匹配“:”预期(第1行,位置4)“您能提供表格和spark数据框的示例吗?