【问题标题】:Pyspark: Equivalent of np.where [duplicate]Pyspark:相当于 np.where [重复]
【发布时间】:2018-09-07 10:52:21
【问题描述】:

Pyspark 中这个操作的等价物是什么?

import pandas as pd
import numpy as np

df = pd.DataFrame({'Type':list('ABBC'), 'Set':list('ZZXY')})
df['color'] = np.where(df['Set']=='Z', 'green', 'red')
print(df)

输出

   Set Type  color
0   Z    A  green
1   Z    B  green
2   X    B    red
3   Y    C    red

【问题讨论】:

    标签: pandas pyspark


    【解决方案1】:

    你正在寻找pyspark.sql.functions.when():

    from pyspark.sql.functions import when, col
    
    df = df.withColumn('color', when(col('Set') == 'Z', 'green').otherwise('red'))
    df.show()
    #+---+----+-----+
    #|Set|Type|color|
    #+---+----+-----+
    #|  Z|   A|green|
    #|  Z|   B|green|
    #|  X|   B|  red|
    #|  Y|   C|  red|
    #+---+----+-----+
    

    如果您有多个条件要检查,您可以将对when() 的调用链接在一起,如this answer 所示。

    【讨论】:

    • 谢谢,你是最棒的:)
    • 这个账号我没有足够的声望,但是我用我的另一个账号做了。
    猜你喜欢
    • 2016-11-29
    • 2016-06-23
    • 1970-01-01
    • 2023-03-25
    • 2021-07-25
    • 2015-05-16
    • 2011-08-25
    • 2020-02-19
    相关资源
    最近更新 更多