假設我在org下面有這樣的資料框:
id |raw
123|{"inn":"123”, "prof": "tkie"}
我需要從 json 列中提取raw所有ids值到新列,該怎么做?
我試過:
org.withColumn('inn', from_json($"raw", MapType(StringType, StringType))).withColumn('inn', col('searchcard'.getItem('inn')))
得到錯誤:
檔案 "", line 1 org.withColumn('inn', from_json($"raw", MapType(StringType, StringType))).withColumn('inn', col('searchcard'.getItem('inn'))) ^ 語法錯誤:無效語法
和:
org.withColumn('inn', from_json("raw", MapType(StringType, StringType))).withColumn('inn', col('searchcard'.getItem('inn')))
錯誤:
AssertionError Traceback (最近一次呼叫最后一次) in () ----> 1 org.withColumn('inn', from_json("raw", MapType(StringType, StringType))).withColumn('inn', col('searchcard) '.getItem('inn')))
/opt/cloudera/parcels/SPARK2/lib/spark2/python/pyspark/sql/types.py in init (self, keyType, valueType, valueContainsNull) 342 False 343 """ - -> 344 斷言 isinstance(keyType,DataType),“keyType 應該是 DataType” 345 斷言 isinstance(valueType,DataType),“valueType 應該是 DataType” 346 self.keyType = keyType AssertionError:keyType 應該是 DataType
uj5u.com熱心網友回復:
這個方法 get_json_object 成功了!
org.withColumn('inn',get_json_object(org.raw, '$.inn')).show(1)
uj5u.com熱心網友回復:
您的代碼包含幾個問題:
$"raw"與 Scala API 一起使用,在 Pyspark 中使用col("raw")或直接作為字串使用"raw"- 使用
StringType或任何其他型別時,在python中需要添加括號StringType() getItem是一個 Column 方法,但您在字串 ('searchcard'.getItem('inn')) 中呼叫它
這是使用from_json函式的完整作業示例更正的相同代碼:
import pyspark.sql.functions as F
from pyspark.sql.types import StringType, MapType
org = spark.createDataFrame([
(123, '{"inn":"123", "prof": "tkie"}')
], ["id", "raw"])
org.withColumn(
'raw',
F.from_json("raw", MapType(StringType(), StringType()))
).select(
'id',
F.col('raw').getItem('inn').alias('inn')
).show()
# --- ---
#| id|inn|
# --- ---
#|123|123|
# --- ---
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/394908.html
