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等。我尝试过
df.select([df.list_1[i] for i in range(5)])
但是由于每个列表中都有大约4000个值,因此上述操作似乎很耗时。最终目标是在结果数据框中找到每一列的中位数。
我使用pyspark。
答案 0 :(得分:1)
您可以查看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_extract
和split
进行此操作。它也适用于字符串中的浮点值。
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)