从PySpark DataFrame中的非null列中选择值

Dav*_*d D 4 python dataframe apache-spark apache-spark-sql pyspark

pyspark数据框缺少值:

tbl = sc.parallelize([
        Row(first_name='Alice', last_name='Cooper'),             
        Row(first_name='Prince', last_name=None),
        Row(first_name=None, last_name='Lenon')
    ]).toDF()
tbl.show()
Run Code Online (Sandbox Code Playgroud)

这是桌子:

  +----------+---------+
  |first_name|last_name|
  +----------+---------+
  |     Alice|   Cooper|
  |    Prince|     null|
  |      null|    Lenon|
  +----------+---------+
Run Code Online (Sandbox Code Playgroud)

我想创建一个新列,如下所示:

  • 如果名字为“无”,请使用姓氏
  • 如果姓氏为“无”,请使用名字
  • 如果它们都存在,则将它们串联
  • 我们可以安全地假设其中至少有一个

我可以构造一个简单的函数:

def combine_data(row):
    if row.last_name is None:
        return row.first_name
    elif row.first_name is None:
        return row.last_name
    else:
        return '%s %s' % (row.first_name, row.last_name)
tbl.map(combine_data).collect()
Run Code Online (Sandbox Code Playgroud)

我确实得到了正确的结果,但是我无法将其作为列追加到表中:tbl.withColumn('new_col', tbl.map(combine_data))结果为AssertionError: col should be Column

将结果转换map为a 的最佳方法是Column什么?有没有一种首选的方法来处理null价值观?

zer*_*323 6

与往常一样,最好直接在本机表示形式上操作,而不是将数据提取到Python:

from pyspark.sql.functions import concat_ws, coalesce, lit, trim

def combine(*cols):
    return trim(concat_ws(" ", *[coalesce(c, lit("")) for c in cols]))

tbl.withColumn("foo", combine("first_name", "last_name")).
Run Code Online (Sandbox Code Playgroud)


Alb*_*nto 4

您只需使用接收两个参数的UDF 。columns

from pyspark.sql.functions import *
from pyspark.sql import Row

tbl = sc.parallelize([
        Row(first_name='Alice', last_name='Cooper'),             
        Row(first_name='Prince', last_name=None),
        Row(first_name=None, last_name='Lenon')
    ]).toDF()

tbl.show()

def combine(c1, c2):
  if c1 != None and c2 != None:
    return c1 + " " + c2
  elif c1 == None:
    return c2
  else:
    return c1

combineUDF = udf(combine)

expr = [c for c in ["first_name", "last_name"]] + [combineUDF(col("first_name"), col("last_name")).alias("full_name")]

tbl.select(*expr).show()

#+----------+---------+------------+
#|first_name|last_name|   full_name|
#+----------+---------+------------+
#|     Alice|   Cooper|Alice Cooper|
#|    Prince|     null|      Prince|
#|      null|    Lenon|       Lenon|
#+----------+---------+------------+
Run Code Online (Sandbox Code Playgroud)