Jul*_*ard 5 python bigdata pyspark
我有一个这样的数据框,如果列n
大于一个,我想将行重复n次:
A B n
1 2 1
2 9 1
3 8 2
4 1 1
5 3 3
Run Code Online (Sandbox Code Playgroud)
然后像这样转换:
A B n
1 2 1
2 9 1
3 8 2
3 8 2
4 1 1
5 3 3
5 3 3
5 3 3
Run Code Online (Sandbox Code Playgroud)
我想我应该使用explode
,但我不明白它的工作原理...
谢谢
jxc*_*jxc 11
随着星火2.4.0+,这是具有内置功能更易于:array_repeat +爆炸:
from pyspark.sql.functions import expr
df = spark.createDataFrame([(1,2,1), (2,9,1), (3,8,2), (4,1,1), (5,3,3)], ["A", "B", "n"])
new_df = df.withColumn('n', expr('explode(array_repeat(n,int(n)))'))
>>> new_df.show()
+---+---+---+
| A| B| n|
+---+---+---+
| 1| 2| 1|
| 2| 9| 1|
| 3| 8| 2|
| 3| 8| 2|
| 4| 1| 1|
| 5| 3| 3|
| 5| 3| 3|
| 5| 3| 3|
+---+---+---+
Run Code Online (Sandbox Code Playgroud)
的爆炸功能返回给定阵列或地图中的每个元素的新行。
利用此功能的一种方法是使用udf
来n
为每行创建一个大小列表。然后爆炸生成的数组。
from pyspark.sql.functions import udf, explode
from pyspark.sql.types import ArrayType, IntegerType
df = spark.createDataFrame([(1,2,1), (2,9,1), (3,8,2), (4,1,1), (5,3,3)] ,["A", "B", "n"])
# use udf function to transform the n value to n times
n_to_array = udf(lambda n : [n] * n, ArrayType(IntegerType()))
df2 = df.withColumn('n', n_to_array(df.n))
# now use explode
df2.withColumn('n', explode(df2.n)).show()
+---+---+---+
| A | B | n |
+---+---+---+
| 1| 2| 1|
| 2| 9| 1|
| 3| 8| 2|
| 3| 8| 2|
| 4| 1| 1|
| 5| 3| 3|
| 5| 3| 3|
| 5| 3| 3|
+---+---+---+
Run Code Online (Sandbox Code Playgroud)