【问题标题】:Selecting values from non-null columns in a PySpark DataFrame从 PySpark DataFrame 中的非空列中选择值
【发布时间】:2016-07-10 19:29:51
【问题描述】:

有一个缺少值的 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()

这是桌子:

  +----------+---------+
  |first_name|last_name|
  +----------+---------+
  |     Alice|   Cooper|
  |    Prince|     null|
  |      null|    Lenon|
  +----------+---------+

我想新建一个列如下:

  • 如果名字为无,则取姓氏
  • 如果姓氏为无,取名
  • 如果它们都存在,则将它们连接起来
  • 我们可以放心地假设其中至少存在一个

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

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()

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

map 的结果转换为Column 的最佳方法是什么?是否有处理null 值的首选方法?

【问题讨论】:

  • 我的回答还不够吗?有什么限制吗?

标签: python apache-spark dataframe pyspark apache-spark-sql


【解决方案1】:

与往常一样,最好直接对原生表示进行操作,而不是向 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")).

【讨论】:

  • 谢谢。您的答案直接针对我给出的示例,但@alberto-bonsanto 的答案对我来说更容易阅读并且更容易根据我的实际需要进行修改
【解决方案2】:

您只需要使用接收两个columns 作为参数的UDF

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|
#+----------+---------+------------+

【讨论】:

  • This 是有时使用select 而不是withColumn 更好的原因
猜你喜欢
  • 1970-01-01
  • 2020-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-14
相关资源
最近更新 更多