我正在使用 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
数据类型,以及在这种情况下,在数据帧貌似值1234
与0
正在丢失。即使我稍后将数据类型转换为 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] 删除。
我来说两句