Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Rename and Drop Columns in Spark DataFrames

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

Comment

You can use withColumnRenamed to rename a column in a DataFrame. You can also do renaming using alias when select columns.

+---+---+---+---+
| _0| _1| _2| _3|
+---+---+---+---+
|  1|  a|foo|3.0|
|  1|  b|bar|4.0|
|  3|  c|foo|5.0|
|  4|  d|bar|7.0|
+---+---+---+---+

Get Column Name

  1. There is no good way to get the name of a Column, unfortunately.

  2. Column._jc.toString()

Column<b'_0'>
"Column<b'_0'>"
'_0'
Column<b'max(_0) AS `_0_max`'>
'max(_0) AS `_0_max`'
Column<b'multialias(max(_0) AS `_0_max`)'>
"Column<b'max(_0) AS `_0_max`'>"

Drop Columns

20/07/19 14:27:45 INFO CodeGenerator: Code generated in 22.343436 ms
20/07/19 14:27:45 INFO CodeGenerator: Code generated in 25.541113 ms
+---+---+
| _2| _4|
+---+---+
|  a|3.0|
|  b|4.0|
|  c|5.0|
|  d|7.0|
+---+---+

Renaming One Column Using withColumnRenamed

+---+---+---+---+
| x1| _2| _3| _4|
+---+---+---+---+
|  1|  a|foo|3.0|
|  2|  b|bar|4.0|
|  3|  c|foo|5.0|
|  4|  d|bar|7.0|
+---+---+---+---+

Renaming One Column Using alias

+---+---+---+---+
| x1| _2| _3| _4|
+---+---+---+---+
|  1|  a|foo|3.0|
|  2|  b|bar|4.0|
|  3|  c|foo|5.0|
|  4|  d|bar|7.0|
+---+---+---+---+

Batch Renaming Using withColumnRenamed

Loading...
+---+---+---+---+
| x1| x2| x3| x4|
+---+---+---+---+
|  1|  a|foo|3.0|
|  2|  b|bar|4.0|
|  3|  c|foo|5.0|
|  4|  d|bar|7.0|
+---+---+---+---+

Batch Renaming Using alias

+---+---+---+---+
| x1| x2| x3| x4|
+---+---+---+---+
|  1|  a|foo|3.0|
|  2|  b|bar|4.0|
|  3|  c|foo|5.0|
|  4|  d|bar|7.0|
+---+---+---+---+