np.where pyspark 数据帧中的逻辑

np.where logic in pyspark dataframe

我正在寻找一种方法,仅当字符的长度大于 2 时,才从数据框列中的字符串中获取第二名之后的字符,并将其放入另一列,否则为空。我在 spark 数据框中还有其他几个列

我有一个如下所示的 Spark 数据框:

animal
======
mo
cat
mouse
snake
reptiles

我想要这样的东西:

remainder
========
null
t
use
ake
ptiles

我可以使用 pandas 数据框中的 np.where 来做到这一点,如下所示

import numpy as np
df['remainder'] = np.where(len(df['animal]) > 2, df['animal].str[2:], 'null)

我如何在 pyspark 数据帧中执行相同的操作

您可以通过 when-otherwise with substring

的组合轻松做到这一点

数据准备

s = StringIO("""
animal
mo
cat
mouse
snake
reptiles
""")

df = pd.read_csv(s,delimiter=',')

sparkDF = sql.createDataFrame(df)

sparkDF.show()

+--------+
|  animal|
+--------+
|      mo|
|     cat|
|   mouse|
|   snake|
|reptiles|
+--------+

When-Otherwise - 子字符串

sparkDF = sparkDF.withColumn('animal_length',F.length(F.col('animal'))) \
            .withColumn('remainder',F.when(F.col('animal_length') > 2
                                               ,F.substring(F.col('animal'),2,1000)
                                              ).otherwise(None)
                       ) \
            .drop('animal_length')

sparkDF.show()

+--------+---------+
|  animal|remainder|
+--------+---------+
|      mo|     null|
|     cat|       at|
|   mouse|     ouse|
|   snake|     nake|
|reptiles|  eptiles|
+--------+---------+