【问题标题】:Error when trying to specify schema for loading a CSV using pyspark尝试指定使用 pyspark 加载 CSV 的架构时出错
【发布时间】:2020-05-15 09:24:43
【问题描述】:

我正在尝试构建一个模式来加载包含以下内容的文件的内容-

  1. movie_id,字符串
  2. 电影名称,字符串
  3. 情节,字符串
  4. 流派,字符串数组

这是一个示例-

这是我的架构定义-

customSchema = types.StructType(types.ArrayType(
                         types.StructField("movie_id", types.StringType(), True),
                         types.StructField("movie_name", types.StringType(), True),
                         types.StructField("plot", types.StringType(), True),
                         types.StructField('genre', 
                         types.ArrayType(types.StringType()), True),
))

这是我得到的错误

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-290-10452c69a6ff> in <module>()
        3   types.StructField("movie_name", types.StringType(), True),
        4   types.StructField("plot", types.StringType(), True),
  ----> 5   types.StructField('genre', types.ArrayType(types.StringType()), True),
        6 ))

TypeError: __init__() takes from 2 to 3 positional arguments but 5 were given

【问题讨论】:

  • 不是machine-learning 问题,请不要发送垃圾邮件无关标签(已删除并替换为apache-spark-sql)。

标签: pyspark apache-spark-sql pyspark-dataframes


【解决方案1】:

StructType()StructField()s 的list

from pyspark.sql.types import *  

customSchema= StructType([StructField("movie_id", IntegerType()),
                        StructField("movie_name", StringType()),
                        StructField("plot", StringType()),
                          StructField("genre", ArrayType(StringType()))])

如果 genre 字符串列 看起来像 "['Indie', 'Drama', 'Action']",请尝试将其转换为字符串数组:

from pyspark.sql import functions as F
df.withColumn("genre", F.split(F.regexp_replace("genre", "\[|]| |'", ""),",")).show(truncate=False)

#+----------------------+
#|genre                 |
#+----------------------+
#|[Indie, Drama, Action]|
#+----------------------+

【讨论】:

    猜你喜欢
    • 2016-04-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-15
    • 1970-01-01
    • 2015-08-04
    • 1970-01-01
    • 2023-03-31
    • 2012-10-15
    相关资源
    最近更新 更多