對于示例火花 df:
sdf = ({'id_col': [25, 13, 15],
'x2': ['b', None, '2'],
'x3': [None, '0', '3'] })
我會擁有:
sdf = ({'id_col': [25, 13, 15],
'x2': [1, 0, 1],
'x3': [0, 1, 1] })
將所有 null 替換為 0,將 notnull 替換為 1。
遵循以下語法:在 pyspark dataframe 中將非空值填充為 1。它通過了自衛隊的所有列。對于我的情況,我需要保持 id_col 的值不變,但在 cols x2 和 x3 上替換為 1 和 0。
我最初嘗試了以下方法:
我將 x2 和 x3 列放在一個串列中:
串列 = ['x2','x3']
然后應用這個:
col_selection = [when(col(c).isNull(),0).otherwise(1).alias(c) for c in sdf[[list]].columns]
我得到了預期的 0 和 1,但我只得到 x2 和 x3 列。當我打電話給 sdf 時,沒有發生變化。如果我在 25 列 sdf 中有 17 列要通過,您能指導我如何僅在 17 列上應用 for 回圈嗎?
謝謝
uj5u.com熱心網友回復:
如果可以的話,一一做
from pyspark.sql import functions as F
import pandas as pd
sdf = pd.DataFrame({'id_col': [25, 13, 15],
'x2': ['b', None, '2'],
'x3': [None, '0', '3'] })
sdf=spark.createDataFrame(sdf)
sdf.withColumns({"x2":F.when(F.col("x2").isNull(),0).otherwise(1),"x3":F.when(F.col("x3").isNull(),0).otherwise(1)}).show()
#output
------ --- ---
|id_col| x2| x3|
------ --- ---
| 25| 1| 0|
| 13| 0| 1|
| 15| 1| 1|
------ --- ---
Note-withColumns 僅適用于 spark 版本 >= 3.3.0
回圈執行
lis=['x2','x3']
for a in lis:
sdf=sdf.withColumn(f"{a}",F.when(F.col(f"{a}").isNull(),0).otherwise(1))
sdf.show()
#output
------ --- ---
|id_col| x2| x3|
------ --- ---
| 25| 1| 0|
| 13| 0| 1|
| 15| 1| 1|
------ --- ---
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/495157.html
