udf在pyspark中对列表进行排序

时间:2017-07-03 14:00:41

标签: apache-spark pyspark

我有一个数据框,其中一个名为stopped的列是:

+--------------------+
|             stopped|
+--------------------+
|[nintendo, dsi, l...|
|[nintendo, dsi, l...|
|    [xl, honda, 500]|
|[black, swan, green]|
|[black, swan, green]|
|[pin, stripe, sui...|
|  [shooting, braces]|
|      [haus, geltow]|
|[60, cm, electric...|
|  [yamaha, yl1, yl2]|
|[landwirtschaft, ...|
|     [wingbar, 9581]|
|       [gummi, 16mm]|
|[brillen, lupe, c...|
|[man, city, v, ba...|
|[one, plus, one, ...|
|     [kapplocheisen]|
|[tractor, door, m...|
|[pro, nano, flat,...|
|[kaleidoscope, to...|
+--------------------+

我想创建另一个包含相同列表但列出关键字的列。

据我了解,我需要创建一个获取并返回列表的udf:

udf_sort = udf(lambda x: x.sort(), ArrayType(StringType()))
ps_clean.select("*", udf_sort(ps_clean["stopped"])).show(5, False)

我得到了:

+---------+----------+---------------------+------------+--------------------------+--------------------------+-----------------+
|client_id|kw_id     |keyword              |max_click_dt|tokenized                 |stopped                   |<lambda>(stopped)|
+---------+----------+---------------------+------------+--------------------------+--------------------------+-----------------+
|710      |4304414582|nintendo dsi lite new|2017-01-06  |[nintendo, dsi, lite, new]|[nintendo, dsi, lite, new]|null             |
|705      |4304414582|nintendo dsi lite new|2017-03-25  |[nintendo, dsi, lite, new]|[nintendo, dsi, lite, new]|null             |
|707      |647507047 |xl honda 500 s       |2016-10-26  |[xl, honda, 500, s]       |[xl, honda, 500]          |null             |
|710      |26308464  |black swan green     |2016-01-01  |[black, swan, green]      |[black, swan, green]      |null             |
|705      |26308464  |black swan green     |2016-07-13  |[black, swan, green]      |[black, swan, green]      |null             |
+---------+----------+---------------------+------------+--------------------------+--------------------------+-----------------+

为什么没有应用排序?

2 个答案:

答案 0 :(得分:2)

x.sort()通常会对列表进行排序(但我怀疑它不会在pyspark数据帧中执行此操作)并返回None。这就是标记为<lambda>(stopped)的列具有所有null值的结果。sorted(x)将对列表进行排序并返回新的已排序副本。所以,用

替换你的udf
udf_sort = udf(lambda x: sorted(x), ArrayType(StringType()))

应该解决你的问题。

或者,您可以使用内置函数sort_array而不是定义自己的udf。

from pyspark.sql.functions import sort_array

ps_clean.select("*", sort_array(ps_clean["stopped"])).show(5, False)

这种方法更清洁,实际上你可以期望获得一些性能提升,因为pyspark不必序列化你的udf。

答案 1 :(得分:1)

将您的udf更改为:

udf_sort = udf(lambda x: sorted(x), ArrayType(StringType()))

on diffrences beetwen .sort().sorted()读取:

What is the difference between `sorted(list)` vs `list.sort()` ? python

相关问题