在pyspark中指定列数据类型

法鲁克·塔什普拉托夫

我正在使用 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)

问题是下地址和公司的Structs在源文件中的列POSTALCODE具有类似的值01234,但是你可以从架构中看到,这列被解读为Long数据类型,以及在这种情况下,在数据帧貌似值12340正在丢失。即使我稍后将数据类型转换为 StringType,0无论如何都会丢失。

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

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

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

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

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

赫里斯托·伊利耶夫

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

第一个是通过将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)
])

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在值子查询中指定列的数据类型

如果您未在SQLite中指定新列的数据类型怎么办?

如何在绘图表中指定数据类型?

在Redshift'CREATE TABLE AS'查询中指定数据类型

如何在map函数中指定数据类型?

使用pyspark获取列的数据类型

从HTTP标头的每一列中指定read_csv中每一列的数据类型

如何在Standard-ML中的数据类型中指定类型约束?

验证pyspark数据框中的列的数据类型

如何在Pandas数据框中指定列类型

从 CXF 公开时如何在 WSDL 中指定数据类型

如何在 Swift 中指定在 URLRequest 中发送的数据类型?

如何在 PyExasol export_to_pandas 中指定数据类型

无法在NumPy中指定结构化数据类型

PySpark 如何遍历 Dataframe 列并更改数据类型?

由于数据类型不匹配PySpark无法解析列

更改 Pyspark 中 Arraytype 列的任何字段的数据类型

fread-指定一列的数据类型

无法在数据类型int上指定列宽

为任意数据类型指定类型

PySpark:连接具有“Struc”数据类型的两列--> 错误:由于数据类型不匹配而无法解析

在 Pyspark 中更改数据类型

列数据类型-MySQL

Pyspark从数据类型为Boolean的数据框中获取列的名称

pyspark 数据框:填充具有不同数据类型的选定列的值

PySpark-显示数据框中的列数据类型计数

根据列的数据类型在pyspark数据框中填充空值

指定axios响应数据类型

如果指定了数据类型 'json' 则出错