PySpark:使用从列创建的元组添加新列

2024-05-04 20:42:13 发布

您现在位置:Python中文网/ 问答频道 /正文

这里我有一个日期框架,创建如下

df = spark.createDataFrame([('a',5,'R','X'),('b',7,'G','S'),('c',8,'G','S')], 
                       ["Id","V1","V2","V3"])

看起来像

+---+---+---+---+
| Id| V1| V2| V3|
+---+---+---+---+
|  a|  5|  R|  X|
|  b|  7|  G|  S|
|  c|  8|  G|  S|
+---+---+---+---+

我想添加一个由V1,V2,V3组成的元组列。

结果应该是

+---+---+---+---+-------+
| Id| V1| V2| V3|V_tuple|
+---+---+---+---+-------+
|  a|  5|  R|  X|(5,R,X)|
|  b|  7|  G|  S|(7,G,S)|
|  c|  8|  G|  S|(8,G,S)|
+---+---+---+---+-------+

我曾尝试使用类似于Python中的syntex,但没有成功:

df.withColumn("V_tuple",list(zip(df.V1,df.V2,df.V3)))

TypeError:zip参数1必须支持迭代。

任何帮助都将不胜感激!


Tags: 框架iddfv3ziplistsparkv2
2条回答

我来自scala,但我相信python中也有类似的方法:

使用^{}包方法:

如果要使用这三列获得StructType方法,请使用如下struct(cols: Column*): Column方法:

from pyspark.sql.functions import struct
df.withColumn("V_tuple",struct(df.V1,df.V2,df.V3))

但是如果你想把它作为一个字符串,你可以像这样使用concat(exprs: Column*): Column方法:

from pyspark.sql.functions import concat
df.withColumn("V_tuple",concat(df.V1,df.V2,df.V3))

使用第二种方法,您可能必须将列强制转换为Strings

我不确定python语法,如果有语法错误,请编辑答案。

希望这对你有帮助。致意

使用struct

from pyspark.sql.functions import struct

df.withColumn("V_tuple", struct(df.V1,df.V2,df.V3))

相关问题 更多 >