在 Pyspark 中使用 where 子句更新列

Viv*_*Viv 1 dataframe apache-spark apache-spark-sql pyspark

如何使用 where 子句更新 Pyspark 数据框中的列?

这类似于此 SQL 操作:

   UPDATE table1 SET alpha1= x WHERE alpha2< 6;
Run Code Online (Sandbox Code Playgroud)

其中 alpha1 和 alpha2 是 table1 的列。

例如:我有一个数据框 table1,其值如下:

表格1

阿尔法1 阿尔法2
3 7
4 5
5 4
6 8

更新后的数据框表1:

阿尔法1 阿尔法2
3 7
x 5
x 4
6 8

如何在 pyspark 数据框中执行此操作?

Ass*_*son 5

您正在寻找when函数:

df = spark.createDataFrame([("3",7),("4",5),("5",4),("6",8)],["alpha1", "alpha2"])
df.show()
>>> +------+------+
>>> |alpha1|alpha2|
>>> +------+------+
>>> |     3|     7|
>>> |     4|     5|
>>> |     5|     4|
>>> |     6|     8|
>>> +------+------+

df2 = df.withColumn("alpha1", pyspark.sql.functions.when(df["alpha2"] < 6, "x").otherwise(df["alpha1"]))
df2.show()
>>>+------+------+
>>>|alpha1|alpha2|
>>>+------+------+
>>>|     3|     7|
>>>|     x|     5|
>>>|     x|     4|
>>>|     6|     8|
>>>+------+------+
Run Code Online (Sandbox Code Playgroud)