![](/img/trans.png)
[英]How can I convert a list of lists in a Dataframe in Pyspark, being each list the values of each attribute?
[英]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 等等。我試過了
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_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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.