从整数列表的PySpark DataFrame数组中快速检索唯一整数?

用户名

假设您有一个Pyspark DataFrame ,df

DataFrame[set_sid_index: array<int>]

看起来像:

+--------------------+
|       set_sid_index|
+--------------------+
|           [8, 0, 1]|
|              [8, 1]|
|                 [9]|
|                 [0]|
|                 [2]|
|           [0, 1, 3]|
|           [8, 0, 1]|
|[22, 2, 6, 0, 1, 21]|
|  [2, 0, 1, 4, 5, 3]|
|              [0, 1]|
|           [0, 1, 3]|
|              [0, 1]|
|                 [9]|
|      [2, 105, 4, 3]|
+--------------------+

和另一个PySpark DataFrame df2

DataFrame[set_sid_index: array<int>]

+--------------------+
|       set_sid_index|
+--------------------+
|           [8, 0, 1]|
+--------------------+

您将如何转换df数组中列表的元素,以便将不是{0, 1, 8}的元素(的唯一元素df2)转换为“ 0”,“ 1”或“ 8”?

-澄清以上段落-

对于我的特定用例,我必须找到uniq,这是整数列表数组中的一组唯一元素。具体地说,在上面给出的示例中,df2只有一个具有唯一值(0、1、8)的列表。实际上,df2将有多个具有重叠值的列表。我需要uniq= unique(df2values)我怎么做?

谢尔盖·布什曼诺夫(Sergey Bushmanov)

我对您的“转换为0或1或8”感到困惑。因此,更准确地说:

如果1st df的元素不在数组[0,1,8]中,则将其转换为 0

有了这个资格,让我们开始吧。

我们有:

from pyspark.sql.functions import udf
from pyspark.sql.types import *
uniq = [8, 0, 1]
sdf.show()
+--------------------+
|       set_sid_index|
+--------------------+
|           [8, 0, 1]|
|              [8, 1]|
|                 [9]|
|                 [0]|
|                 [2]|
|           [0, 1, 3]|
|           [8, 0, 1]|
|[22, 2, 6, 0, 1, 21]|
|  [2, 0, 1, 4, 5, 3]|
|              [0, 1]|
|           [0, 1, 3]|
|              [0, 1]|
|                 [9]|
|      [2, 105, 4, 3]|
+--------------------+


sdf.printSchema()
root
 |-- set_sid_index: array (nullable = true)
 |    |-- element: long (containsNull = true)

现在让我们定义一个简单的udf并将其应用:

convertToZero = udf(lambda x: [0 if i not in uniq else i for i in x], ArrayType(IntegerType()))
sdf.withColumn('set_sid_index', convertToZero(sdf['set_sid_index'])).show(truncate=False)
+------------------+
|set_sid_index     |
+------------------+
|[8, 0, 1]         |
|[8, 1]            |
|[0]               |
|[0]               |
|[0]               |
|[0, 1, 0]         |
|[8, 0, 1]         |
|[0, 0, 0, 0, 1, 0]|
|[0, 0, 1, 0, 0, 0]|
|[0, 1]            |
|[0, 1, 0]         |
|[0, 1]            |
|[0]               |
|[0, 0, 0, 0]      |
+------------------+

更新

假设您没有可用的uniq数组。

然后:

sdf2.show()
+--------------------+
|       set_sid_index|
+--------------------+
|[22, 2, 6, 0, 1, 21]|
|  [2, 0, 1, 4, 5, 3]|
|              [0, 1]|
+--------------------+

x = sdf2.withColumn('set_sid_index', explode(sdf2['set_sid_index'])).drop_duplicates().collect()
uniq = [i[0] for i in x]
uniq
[0, 22, 6, 5, 1, 3, 2, 4, 21]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章