我有一个 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]))
关于apache-spark - 如何使用分隔符连接 PySpark 中的多列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59032577/