我有以下資料框,每列包含相同大小的值串列
-------- -------------------- -------------------- -------------------- --------------
|Country_1| |Country_2| |Country_3| |Country_4|
-------------------- -------------------- -------------------- --------------------
|[1, 2, 3, 4, 5, 6 ] | [x1, x2, x3, x4, x5, x6 ]|[y1, y2, y3, y4, y5, y6 ] |[v1, v2, v3, v4, v5, v6 ]
我需要將每個元素串列轉換為一行,以便進一步詳細說明,從我在這篇文章中看到的內容來看,我應該使用explode函式以某種方式結束,如下所示:
Country_1 Country_2 Country_3 Country_4
1 x1 y1 v1
2 x2 y2 v2
3 x3 y3 v3
4 x4 y4 v4
5 x5 y5 v5
6 x6 y6 v6
我已經嘗試了下面的代碼,但到目前為止還沒有成功。
data.withColumn("Country_1Country_2", F.arrays_zip("Country_1","Country_2")).select(*, F.explode("Country_1Country_2").alias("tCountry_1Country_2")).select(*, "tCountry_1Country_2.Country_1", col("Country_1Country_2.Country_2")).show()
uj5u.com熱心網友回復:
# This is not part of the solution, just creation of the data sample
# df = spark.sql("select stack(1, array(1, 2, 3, 4, 5, 6) ,array('x1', 'x2', 'x3', 'x4', 'x5', 'x6') ,array('y1', 'y2', 'y3', 'y4', 'y5', 'y6') ,array('v1', 'v2', 'v3', 'v4', 'v5', 'v6')) as (Country_1, Country_2,Country_3,Country_4)")
df.selectExpr('inline(arrays_zip(*))').show()
--------- --------- --------- ---------
|Country_1|Country_2|Country_3|Country_4|
--------- --------- --------- ---------
| 1| x1| y1| v1|
| 2| x2| y2| v2|
| 3| x3| y3| v3|
| 4| x4| y4| v4|
| 5| x5| y5| v5|
| 6| x6| y6| v6|
--------- --------- --------- ---------
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/441260.html
標籤:数据框 pyspark apache-spark-sql rdd
上一篇:在pandasDataFrame中查找具有更多0值的行
下一篇:重新編碼R中的現有列
