如何找到 pyspark 数据框中每个列表的第一个值的中值?

How Can I find the median of the first values of each list in pyspark dataframe?

values = [(u'[23,4,77,890,455]',10),(u'[11,2,50,1,11]',20),(u'[10,5,1,22,04]',30)]
df = sqlContext.createDataFrame(values,['list','A'])
df.show()

+-----------------+---+
|           list_1|  A|
+-----------------+---+
|[23,4,77,890,455]| 10|
|   [11,2,50,1,11]| 20|
|   [10,5,1,22,04]| 30|
+-----------------+---+

我想将上面的 spark 数据帧转换成一个帧,这样 "list_1" 列的每个列表中的第一个元素应该在一列中,即第一列 4,2,5 中的 23,11,10第二列 etc.I 已尝试

df.select([df.list_1[i] for i in range(5)])

但由于我在每个列表中有大约 4000 个值,上述操作似乎很耗时。最终目标是在结果数据框中找到每一列的中位数。

我用的是pyspark。

你可以看看posexplode。 我使用了您的小示例,并将数据框转换为另一个数据框,其中包含 5 列以及每行中数组中的相应值。

from pyspark.sql.functions import *
df1 = spark.createDataFrame([([23,4,77,890,455],10),([11,2,50,1,11],20),\
([10,5,1,22,04],30)], ["list1","A"])
df1.select(posexplode("list1"),"list1","A")\ #explodes the array and creates multiple rows for each element with the position in the columns "col" and "pos"
.groupBy("list1","A").pivot("pos")\          #group by your initial values and take the "pos" column as pivot to create 1 new column per element here
.agg(max("col")).show(truncate=False)        #collect the values

输出:

+---------------------+---+---+---+---+---+---+
|list1                |A  |0  |1  |2  |3  |4  |
+---------------------+---+---+---+---+---+---+
|[10, 5, 1, 22, 4]    |30 |10 |5  |1  |22 |4  |
|[11, 2, 50, 1, 11]   |20 |11 |2  |50 |1  |11 |
|[23, 4, 77, 890, 455]|10 |23 |4  |77 |890|455|
+---------------------+---+---+---+---+---+---+

当然,之后您可以继续计算单个数组值的平均值或任何您想要的值。

如果您的 list1 列包含字符串而不是直接数组,您需要先提取数组。你可以用 regexp_extractsplit 来做到这一点。它也适用于字符串中的浮点值。

df1 = spark.createDataFrame([(u'[23.1,4,77,890,455]',10),(u'[11,2,50,1.1,11]',20),(u'[10,5,1,22,04.1]',30)], ["list1","A"])
df1 = df1.withColumn("list2",split(regexp_extract("list1","(([\d\.]+,)+[\d\.]+)",1),","))
df1.select(posexplode("list2"),"list1","A").groupBy("list1","A").pivot("pos").agg(max("col")).show(truncate=False)