[英]How to read JSON file (Spark/Pyspark) with dots in column names using inferred schema?
我正在動態導入 JSON 文件(將多個文件名並行發送到腳本)並且我的一個文件在字段名稱中包含點。
當它被讀入數據幀進行處理時,模式推斷將其分解為嵌套結構(即“ABC”-> A [B [C]])。
有沒有辦法在不分解包含點的列名的情況下從文件中讀取列?
我知道反引號可以限定列名,但由於我無法在讀取 JSON 文件之前明確定義架構,因此無法執行此操作。
df = sqlContext.read.option('multiline','true').json(<location>)
df.printSchema()
我看到“PO Replacement Cost”字段變為:
|-- P: struct (nullable = true)
| |-- O: struct (nullable = true)
| | |-- Replacement Cost: double (nullable = true)
col 函數中的點符號
col('colName.nestCol.nestNestCol.etc')
from pyspark.sql.functions import col
df.select( col('colName.nestCol').alias('nestCol') )
df.where( col('colName.nestCol') == 'value')
編輯:對不起,我誤讀了你的問題。 試試這個,看看它是否有效。
.withColumn(
'p', # Overwrite your nested struct with the new nested column
struct(
col( 'p.*' ),
lit( col('p.a.b.c') ).alias( 'abc' ) # Renaming
)
)\
.withColumn(
'p',
col( 'p' ).dropFields( col('a.b.c') ) # Remove the ugly named column
)
如果您不需要將列保留在嵌套結構中,您可以做一個簡單的
select( col('p.a.b.c').alias('abc') )
這是將 abc 列移出嵌套結構。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.