【问题标题】:Specify column datatype in pyspark在 pyspark 中指定列数据类型
【发布时间】:2021-11-14 00:01:13
【问题描述】:

我正在使用 Pyspark sql 读取 xml 文件并将其加载为数据框。架构看起来像这样:

    root
 |-- AuditFileCountry: string (nullable = true)
 |-- AuditFileDateCreated: date (nullable = true)
 |-- AuditFileVersion: double (nullable = true)
 |-- Company: struct (nullable = true)
 |    |-- Address: struct (nullable = true)
 |    |    |-- City: string (nullable = true)
 |    |    |-- Country: string (nullable = true)
 |    |    |-- Number: string (nullable = true)
 |    |    |-- PostalCode: long (nullable = true)
 |    |    |-- StreetName: string (nullable = true)
 |    |-- BankAccount: struct (nullable = true)
 |    |    |-- BankAccountNumber: string (nullable = true)
 |    |    |-- CurrencyCode: string (nullable = true)

问题是源文件中 Address 和 Company Structs 下的 PostalCode 列具有类似 01234 的值,但是从架构中可以看出,该列被读取为 Long 数据类型,在这种情况下数据框中的值看起来像1234,而0 丢失了。即使我稍后将数据类型转换为 StringType,0 无论如何都会丢失。

在将数据加载到数据框时,有没有办法将此列的数据类型指定为StringType?

我知道我可以使用类似的东西来做到这一点

schema = StructType([
    StructField('PostalCode', StringType(), True)
])

然后在加载数据时传递这个模式, 但是数据框的架构是嵌套的,您似乎无法像那样简单地指定该列的数据类型。

知道如何解决这个问题吗?任何帮助将不胜感激!

【问题讨论】:

  • 假设您使用 Spark 的 Databricks XML 数据源,您可以将阅读器的 inferSchema 选项设置为 False,XML 中的所有字段都将被视为字符串。
  • @HristoIliev,谢谢,成功了!

标签: python xml apache-spark pyspark


【解决方案1】:

您不能简单地为单个输入列提供数据类型。有两种选择。

第一个是通过将阅读器的inferSchema选项设置为False来完全禁用模式推断:

spark.read \
  .format('xml') \
  .option('inferSchema', False) \
  ...

这将导致数据集中的所有 XML 字段都表示为字符串,您需要在必要时手动转换。如果架构是固定的,更好的选择是提供完整的架构。在你的情况下,这将是这样的:

schema = StructType([
  StructField('AuditFileCountry', StringType, True),
  StructField('AuditFileDateCreated', DateType, True),
  StructField('AuditFileVersion', DoubleType, True),
  StructField('Company', StructType([
    StructField('Address', StructType([
      StructField('City', StringType, True),
      StructField('Country', StringType, True),
      StructField('Number', StringType, True),
      StructField('PostalCode', StringType, True),
      StructField('StreetName', StringType, True)
    ], True),
    StructType('BankAccount', StructType([
      StructField('BankAccountNumber', StringType, True),
      StructField('CurrencyCode', StringType, True)
    ], True)
  ], True)
])

【讨论】:

    猜你喜欢
    • 2019-01-02
    • 2018-02-19
    • 2018-01-09
    • 2021-02-14
    • 2021-12-09
    • 1970-01-01
    • 2019-08-31
    • 2020-05-15
    • 2018-01-31
    相关资源
    最近更新 更多