ver*_*cla 4 apache-spark apache-spark-sql pyspark
我有一个pyspark Dataframe,我想加入 3 列。
id | column_1 | column_2 | column_3
--------------------------------------------
1 | 12 | 34 | 67
--------------------------------------------
2 | 45 | 78 | 90
--------------------------------------------
3 | 23 | 93 | 56
--------------------------------------------
Run Code Online (Sandbox Code Playgroud)
我想加入 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
-------------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)
我怎样才能在 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")))
Run Code Online (Sandbox Code Playgroud)
用于concat将所有列与-分隔符连接起来,您需要使用lit.
如果它不直接工作,您可以使用cast将列类型更改为字符串,col("column_1").cast("string")
更新:
或者您可以使用内置函数使用更动态的方法 concat_ws
pyspark.sql.functions.concat_ws(sep, *cols)
Run Code Online (Sandbox Code Playgroud)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]))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3343 次 |
| 最近记录: |