【问题标题】:How to fill a column in a pyspark dataframe with the value of another column based on a condition on some other columns如何根据其他列的条件用另一列的值填充 pyspark 数据框中的列
【发布时间】:2019-06-06 00:11:12
【问题描述】:

谁能回答下面链接上的问题,但在 pyspark 中?

how to fill a column with the value of another column based on a condition on some other columns?

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

假设我们在pyspark中有一个dataframe如下:

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<col1col2 不是null,我想用col1 替换col4 的值

所以结果应该是

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

任何帮助将不胜感激。

【问题讨论】:

  • 使用来自pyspark.sql.functionswhen() 函数,它的工作方式类似于if else 子句。

标签: dataframe pyspark conditional-statements


【解决方案1】:
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|
+----+----+----+----+

【讨论】:

    【解决方案2】:

    这解决了你的问题:

    from pyspark.sql.functions import col, when
    
    condition_col = (col('col4') < col('col1')) & (col('col2').isNotNull())
    df = df.withColumn('col4', when(condition_col, col('col1')).otherwise(col('col4')))
    

    when(cond, result1).otherwise(result2) 的作用类似于带有列的 if / else 子句。

    对于列逻辑运算符,使用:&amp; for and|or~not

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-21
      • 1970-01-01
      • 1970-01-01
      • 2020-03-16
      • 2017-12-26
      • 2022-01-15
      • 2020-10-27
      相关资源
      最近更新 更多