我有在 PySpark SQL 中處理的資料,如下所示:
--------- ----------------
|user_id |user_ids |
--------- ----------------
|null |[479534, 1234] |
|null |[1234] |
|null |[479535] |
|null |[479535, 479536]|
|null |[1234] |
|null |[479535] |
|1234567 |null |
|1234567 |null |
|777 |null |
|888 |null |
|null |null |
--------- ----------------
我只需要一user_id列,從 爆炸額外的行user_ids,所以是這樣的:
---------
|user_id |
---------
|479534 |
|1234 |
|1234 |
|479535 |
|479535 |
|479536 |
|1234 |
|479535 |
|1234567 |
|1234567 |
|777 |
|888 |
|null |
---------
我怎樣才能做到這一點?
我試過了:
.withColumn("user_ids", F.explode_outer("user_ids"))
.withColumn("user_id", F.coalesce(df["user_id"], df["user_ids"]))
但是我得到了:
cannot resolve 'coalesce(user_id, user_ids)' due to data type mismatch: input to function coalesce should all be the same type, but it's [bigint, array<bigint>];
所以我認為withColumn在這種情況下不能使用另一個創建的列。
uj5u.com熱心網友回復:
您不會在爆炸后保存資料幀,因此不要將列參考為,df['col']而只是呼叫F.col('col'). 例如,
df.withColumn('user_ids', F.explode_outer('user_ids'))
.withColumn('user_id', F.coalesce(F.col('user_id'), F.col('user_ids')))
這是我的審判。
from pyspark.sql import functions as f
df = spark.createDataFrame([[None, [479534, 1234]], [1234567, None]], ['user_id', 'user_ids'])
df.show()
------- --------------
|user_id| user_ids|
------- --------------
| null|[479534, 1234]|
|1234567| null|
------- --------------
df.withColumn('user_ids', f.explode_outer('user_ids')) \
.withColumn('user_id', f.coalesce(f.col('user_id'), f.col('user_ids'))) \
.drop('user_ids') \
.show()
-------
|user_id|
-------
| 479534|
| 1234|
|1234567|
-------
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/370294.html
標籤:Python 阿帕奇火花 火花 apache-spark-sql
上一篇:PySpark-視窗函式導致新列
