无法合并数据块中的类型<class 'pyspark.sql.types.StringType'>和<class 'pyspark.sql.types.LongType'>

问题描述 投票:0回答:1

我有一个数据框 df。我想将其转换为 Spark 数据框。所以我用运行时版本7的databricks编写了它

df_s=spark.createDataFrame(df)

但是我收到错误消息为

TypeError: value of map value of map field elements: Can not merge type <class 'pyspark.sql.types.StringType'> and <class 'pyspark.sql.types.LongType'>

我的数据框中没有任何字段名称

map value
。你能帮我解决这个问题吗?

python pyspark databricks
1个回答
0
投票

manoj 的一个非常好的例子:

https://sqlwithmanoj.com/2021/04/08/python-error-while-converting-pandas-dataframe-or-python-list-to-spark-dataframe-can-not-merge-type/

import pandas as pd
pd_df = pd.DataFrame([(101, 'abc'), 
                      ('def', 201), 
                      ('xyz', 'pqr')], 
                     columns=['col1', 'col2'])
 
df = spark.createDataFrame(pd_df)
display(df)

输出

TypeError: field col1: Can not merge type <class 'pyspark.sql.types.LongType'> and <class 'pyspark.sql.types.StringType'>

由于列中数据类型混合,Spark 无法推断列的正确数据类型。

在这种情况下,您只需要通过创建新模式并在 createDataFrame() 中使用它来显式告诉 Spark 使用正确的数据类型

import pandas as pd
pd_df = pd.DataFrame([(101, 'abc'), 
                      ('def', 201), 
                      ('xyz', 'pqr')], 
                     columns=['col1', 'col2'])
 
from pyspark.sql.types import *
df_schema = StructType([StructField("col1", StringType(), True)\
                       ,StructField("col2", StringType(), True)])
 
df = spark.createDataFrame(pd_df, schema=df_schema)
display(df)
© www.soinside.com 2019 - 2024. All rights reserved.