我有一个pyspark Dataframe
,我想加入3列。
id | column_1 | column_2 | column_3
--------------------------------------------
1 | 12 | 34 | 67
--------------------------------------------
2 | 45 | 78 | 90
--------------------------------------------
3 | 23 | 93 | 56
--------------------------------------------
我想加入 3 列:column_1, column_2, column_3
在有值"-"
之间只添加一个
预期结果:
id | column_1 | column_2 | column_3 | column_join
-------------------------------------------------------------
1 | 12 | 34 | 67 | 12-34-67
-------------------------------------------------------------
2 | 45 | 78 | 90 | 45-78-90
-------------------------------------------------------------
3 | 23 | 93 | 56 | 23-93-56
-------------------------------------------------------------
我怎样才能在 pyspark 中做到这一点? 谢谢
这很简单:
from pyspark.sql.functions import col, concat, lit
df = df.withColumn("column_join", concat(col("column_1"), lit("-"), col("column_2"), lit("-"), col("column_3")))
使用concat
将所有列与-
分隔符连接起来,为此需要使用lit
。
如果它不能直接工作,您可以使用cast
将列类型更改为字符串,col("column_1").cast("string")
更新:
或者,您可以使用内置函数concat_ws
使用更动态的方法
pyspark.sql.functions.concat_ws(sep, *cols(
Concatenates multiple input string columns together into a single string column, using the given separator. >>> df = spark.createDataFrame([('abcd','123')], ['s', 'd']) >>> df.select(concat_ws('-', df.s, df.d).alias('s')).collect() [Row(s=u'abcd-123')]
代码:
from pyspark.sql.functions import col, concat_ws
concat_columns = ["column_1", "column_2", "column_3"]
df = df.withColumn("column_join", concat_ws("-", *[F.col(x) for x in concat_columns]))
这是一种generic/dynamic
方法,而不是manually
连接它。我们所需要的只是指定我们需要连接的列。
# Importing requisite functions.
from pyspark.sql.functions import col, udf
# Creating the DataFrame
df = spark.createDataFrame([(1,12,34,67),(2,45,78,90),(3,23,93,56)],['id','column_1','column_2','column_3'])
现在,指定我们要连接的列列表,用-
分隔。
list_of_columns_to_join = ['column_1','column_2','column_3']
最后,创建一个UDF
。请注意,基于UDF
的解决方案隐含地较慢。
def concat_cols(*list_cols):
return '-'.join(list([str(i) for i in list_cols]))
concat_cols = udf(concat_cols)
df = df.withColumn('column_join', concat_cols(*list_of_columns_to_join))
df.show()
+---+--------+--------+--------+-----------+
| id|column_1|column_2|column_3|column_join|
+---+--------+--------+--------+-----------+
| 1| 12| 34| 67| 12-34-67|
| 2| 45| 78| 90| 45-78-90|
| 3| 23| 93| 56| 23-93-56|
+---+--------+--------+--------+-----------+