【问题标题】:TypeError: element in array field Category: Can not merge type <class 'pyspark.sql.types.StringType'> and <class 'pyspark.sql.types.DoubleType'>TypeError:数组字段中的元素类别:无法合并类型 <class 'pyspark.sql.types.StringType'> 和 <class 'pyspark.sql.types.DoubleType'>
【发布时间】:2018-12-12 01:38:55
【问题描述】:

我正在使用 Pandas 读取 csv 文件,它是一个两列数据框,然后我尝试转换为 spark 数据框。代码是:

from pyspark.sql import SQLContext
sqlCtx = SQLContext(sc)
sdf = sqlCtx.createDataFrame(df)

数据框:

print(df) 

给出这个:

    Name    Category
0   EDSJOBLIST apply at www.edsjoblist.com  ['biotechnology', 'clinical', 'diagnostic', 'd...
1   Power Direct Marketing  ['advertising', 'analytics', 'brand positionin...
2   CHA Hollywood Medical Center, L.P.  ['general medical and surgical hospital', 'hea...
3   JING JING GOURMET   [nan]
4   TRUE LIFE KINGDOM MINISTRIES    ['religious organization']
5   fasterproms ['microsoft .net']
6   STEREO ZONE ['accessory', 'audio', 'car audio', 'chrome', ...
7   SAN FRANCISCO NEUROLOGICAL SOCIETY  [nan]
8   Fl Advisors ['comprehensive financial planning', 'financia...
9   Fortunatus LLC  ['bottle', 'bottling', 'charitable', 'dna', 'f...
10  TREADS LLC  ['retail', 'wholesaling']

谁能帮我解决这个问题?

【问题讨论】:

  • 您的 pandas 数据框列的类型与错误提示的不同
  • 如果您edit 提出您的问题并包含print(df.dtypes) 的输出和您的一小部分数据样本,将会很有帮助。

标签: python pandas dataframe pyspark apache-spark-sql


【解决方案1】:

Spark 可能难以处理 object 数据类型。一个潜在的解决方法是首先将所有内容都转换为字符串:

sdf = sqlCtx.createDataFrame(df.astype(str))

这样做的一个后果是,包括nan 在内的所有内容都将转换为字符串。您需要注意正确处理这些转换并将列转换为适当的类型。

例如,如果您有一个带有浮点值的列 "colA",您可以使用以下内容将字符串 "nan" 转换为 null

from pyspark.sql.functions import col, when
sdf = sdf.withColumn("colA", when(col("colA") != "nan", col("colA").cast("float")))

【讨论】:

  • 感谢您的帮助。我按照你的建议做了,但是现在,我收到了这个错误: FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Yash\\AppData\\Local\\Temp\\spark-912d2316 -6f98-469a-8abb-f6f4f99b6060\\pyspark-4be513ad-a898-4a41-a911-be158ff813b5\\tmppqmxo4ou'
  • 这看起来与这个问题完全无关。您是否尝试重新启动您的火花上下文?
猜你喜欢
  • 1970-01-01
  • 2020-05-18
  • 1970-01-01
  • 2016-08-16
  • 2019-04-29
  • 1970-01-01
  • 2020-02-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多