다른 열의 JSON 표현 인 새 열을 만들고 싶습니다. 목록의 키, 값 쌍.
출처:
유래 | 목적지 | 카운트 |
---|---|---|
토론토 | 오타와 | 5 |
몬트리올 | 밴쿠버 | 10 |
내가 원하는 것 :
유래 | 목적지 | 카운트 | json |
---|---|---|---|
토론토 | 오타와 | 5 | [{ "origin": "toronto"}, { "destination", "ottawa"}, { "count": "5"}] |
몬트리올 | 밴쿠버 | 10 | [{ "origin": "montreal"}, { "destination", "vancouver"}, { "count": "10"}] |
(모든 것이 문자열이 될 수 있지만 중요하지 않습니다).
나는 다음과 같은 것을 시도했다.
df.withColumn('json', to_json(struct(col('origin'), col('destination'), col('count'))))
그러나 key:value
하나의 개체에 모든 쌍이 있는 열을 만듭니다 .
{"origin":"United States","destination":"Romania"}
UDF없이 가능합니까? 감사!
이것을 해킹하는 방법 :
import pyspark.sql.functions as F
df2 = df.withColumn(
'json',
F.array(
F.to_json(F.struct('origin')),
F.to_json(F.struct('destination')),
F.to_json(F.struct('count'))
).cast('string')
)
df2.show(truncate=False)
+--------+-----------+-----+--------------------------------------------------------------------+
|origin |destination|count|json |
+--------+-----------+-----+--------------------------------------------------------------------+
|toronto |ottawa |5 |[{"origin":"toronto"}, {"destination":"ottawa"}, {"count":"5"}] |
|montreal|vancouver |10 |[{"origin":"montreal"}, {"destination":"vancouver"}, {"count":"10"}]|
+--------+-----------+-----+--------------------------------------------------------------------+
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다