[英]How to rename multiple column names as single column?
I have a table which has columns [col1, col2, col3.... col9].我有一个包含列 [col1, col2, col3.... col9] 的表。 I want to merge all the columns data into one column as col in python?
我想在 python 中将所有列数据合并为一列作为 col?
from pyspark.sql.functions import concat
values = [('A','B','C','D'),('E','F','G','H'),('I','J','K','L')]
df = sqlContext.createDataFrame(values,['col1','col2','col3','col4'])
df.show()
+----+----+----+----+
|col1|col2|col3|col4|
+----+----+----+----+
| A| B| C| D|
| E| F| G| H|
| I| J| K| L|
+----+----+----+----+
req_column = ['col1','col2','col3','col4']
df = df.withColumn('concatenated_cols',concat(*req_column))
df.show()
+----+----+----+----+-----------------+
|col1|col2|col3|col4|concatenated_cols|
+----+----+----+----+-----------------+
| A| B| C| D| ABCD|
| E| F| G| H| EFGH|
| I| J| K| L| IJKL|
+----+----+----+----+-----------------+
using Spark SQL使用火花 SQL
new_df=sqlContext.sql("SELECT CONCAT(col1,col2,col3,col3) FROM df")
Using Non Spark SQL way you can use Concat function使用非 Spark SQL 方式,您可以使用 Concat function
new_df = df.withColumn('joined_column', concat(col('col1'),col('col2'),col('col3'),col('col4'))
In Spark(pySpark) for reasons, there is no edit of existing data.由于某些原因,在 Spark(pySpark) 中,没有对现有数据进行编辑。 What you can do is create a new column.
您可以做的是创建一个新列。 Please check the following link.
请检查以下链接。
How do I add a new column to a Spark DataFrame (using PySpark)? 如何向 Spark DataFrame(使用 PySpark)添加新列?
Using a UDF function , you can aggregate/combine all those values in a row and return you as a single value.使用UDF function ,您可以将所有这些值聚合/组合成一行并将您作为单个值返回。
Few cautions, please look out for following data issues while aggregation几点注意事项,聚合时请注意以下数据问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.