Dataframe 如何根据其他列上的条件,使用另一列的值填充pyspark数据帧中的列

Dataframe 如何根据其他列上的条件,使用另一列的值填充pyspark数据帧中的列,dataframe,pyspark,conditional-statements,Dataframe,Pyspark,Conditional Statements,除了pyspark,还有人能在下面的链接上回答这个问题吗 我在这里再次重复这个问题: 假设pyspark中有一个数据帧,如下所示: col1 | col2 | col3 | col4 22 | null | 23 | 56 12 | 54 | 22 | 36 48 | null | 2 | 45 76 | 32 | 13 | 6 23 | null | 43 | 8 67 | 54 | 56 | 64 16 | 32

除了pyspark,还有人能在下面的链接上回答这个问题吗

我在这里再次重复这个问题:

假设pyspark中有一个数据帧,如下所示:

col1 | col2 | col3 | col4 
22   | null | 23   |  56
12   |  54  | 22   |  36
48   | null | 2    |  45
76   | 32   | 13   |  6
23   | null | 43   |  8
67   | 54   | 56   |  64
16   | 32   | 32   |  6
3    | 54   | 64   |  8
67   | 4    | 23   |  64

如果col4解决了您的问题,我想用col1替换col4的值:

从pyspark.sql.functions导入col,当 条件_col=col'col4' 对于列逻辑运算符,使用:&For and;|为了或;~对于not。

使用pyspark.sql.functions中的when函数,其工作原理与if-else子句类似。
col1 | col2 | col3 | col4 
22   | null  | 23   |  56
12   |  54   | 22   |  36
48   | null  | 2    |  45
76   | 32    | 13   |  76
23   | null  | 43   |  8
67   | 54    | 56   |  67
16   | 32    | 32   |  16
3    | 54    | 64   |  8
67   | null  | 23   |  64
from pyspark.sql.functions import when, col
values = [(22  ,None ,23  , 56), (12, 54, 22, 36), (48 ,None,2 , 45), (76, 32, 13, 6), (23, None, 43, 8), 
(67, 54, 56, 64), (16, 32, 32, 6), (3, 54, 64, 8), (67, 4, 23, 64)]
df = sqlContext.createDataFrame(values,['col1','col2','col3','col4'])
df.show()
+----+----+----+----+
|col1|col2|col3|col4|
+----+----+----+----+
|  22|null|  23|  56|
|  12|  54|  22|  36|
|  48|null|   2|  45|
|  76|  32|  13|   6|
|  23|null|  43|   8|
|  67|  54|  56|  64|
|  16|  32|  32|   6|
|   3|  54|  64|   8|
|  67|   4|  23|  64|
+----+----+----+----+

df = df.withColumn('col4',when((col('col4')<col('col1')) & col('col2').isNotNull(),col('col1')).otherwise(col('col4')))
df.show()
+----+----+----+----+
|col1|col2|col3|col4|
+----+----+----+----+
|  22|null|  23|  56|
|  12|  54|  22|  36|
|  48|null|   2|  45|
|  76|  32|  13|  76|
|  23|null|  43|   8|
|  67|  54|  56|  67|
|  16|  32|  32|  16|
|   3|  54|  64|   8|
|  67|   4|  23|  67|
+----+----+----+----+