【问题标题】:Writing from pandas dataframe to DataBricks database table从 pandas 数据框写入 DataBricks 数据库表
【发布时间】:2021-09-15 07:53:26
【问题描述】:

我在 Azure DataBricks 中有一个已包含数据的数据库表 - 我需要将数据附加到该表。

我有我想要附加到我的数据库的 pandas 数据框 (df_allfeatures)

我用来写入数据库表的函数:

def write_to_delta(df_name, db_name, table_name, write_mode, num_part=10):
    df_name \
        .repartition(num_part) \
        .write \
        .mode(write_mode) \
        .insertInto("{}.{}".format(db_name, table_name), overwrite=True)

当使用该函数通过数据库写入时:

df_allfeatures = spark.createDataFrame(df_allfeatures)
write_to_delta(df_allfeatures, 'production', 'feed_to_output_all_features', 'append', num_part=10)

但是我不断收到错误“ AnalysisException:无法将不兼容的数据写入表'production.feed_to_output_all_features':“

被挑出的列如下:

“AnalysisException:无法将不兼容的数据写入表'production.feed_to_output_all_features':

  • 无法安全地将“LEAD_CONCENTRATE_GRADES_PB”:字符串转换为双精度
  • 无法安全地投射“TAILINGS_RECOVERIES_PB”:时间戳加倍
  • 无法安全地将“DATE”强制转换为时间戳”

我已经更改了数据类型来纠正这个错误:

df_allfeatures = df_allfeatures.astype({"LEAD_CONCENTRATE_GRADES_PB": 'float32'}) 
df_allfeatures = df_allfeatures.astype({"TAILINGS_RECOVERIES_PB": 'float32'})
df_allfeatures['DATE'] = pd.to_datetime(df_allfeatures['DATE'])

但我总是遇到同样的错误

【问题讨论】:

    标签: python pandas azure-databricks


    【解决方案1】:

    按照以下方法将字符串数据类型转换为双精度。

    以下是一些将 String 类型转换为 Double 类型的 PySpark 示例

    #Using withColumn() examples
    df.withColumn("salary",df.salary.cast('double'))
    df.withColumn("salary",df.salary.cast(DoubleType()))
    df.withColumn("salary",col("salary").cast('double'))
    
    # Rounds it to 2 digits
    df.withColumn("salary",round(df.salary.cast(DoubleType()),2))
    
    # Using select
    df.select("firstname",col("salary").cast('double').alias("salary"))
    
    # Using select expression
    df.selectExpr("firstname","cast(salary as double) salary")
    
    # using SQL to Cast
    spark.sql("SELECT firstname,DOUBLE(salary) as salary from CastExample")
    

    有关更多此类示例,请点击此链接 - PySpark Convert String Type to Double Type

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-06
      • 2014-11-21
      • 1970-01-01
      • 2020-03-25
      • 2017-02-17
      • 1970-01-01
      • 2018-05-12
      • 2019-03-21
      相关资源
      最近更新 更多