apache-spark - 如何使用分隔符连接 PySpark 中的多列?

标签 apache-spark pyspark apache-spark-sql

我有一个 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/

相关文章:

apache-spark - 在 Spark 流中聚合来自不同微批处理的数据

amazon-dynamodb - 从 Spark 程序连接 DynamoDB 以使用 Python 从一张表中加载所有项目?

pyspark - 计算 SPARKSQL 中重复行的数量

python - 值错误: Length of object (3) does not match with length of fields

python - 如何修改/转换数据框的列?

python - 在 PySpark 中将十进制解码为二进制信息

python - Spark - 创建嵌套数据框

apache-spark - 我有56列的表格,想加载46列的数据,我该怎么办?

python - 在AWS EMR上``搜索时找不到有效的SPARK_HOME''

python - 从数据框中获取列总和,包括 map 列 - PySpark