Pyspark:相当于np.where

时间:2018-03-28 16:34:05

标签: pandas pyspark

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

1 个答案:

答案 0 :(得分:2)

您正在寻找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所示。

相关问题