Is there any nicer way to prefix or rename all or multiple columns at the same time of a given SparkSQL DataFrame
than calling multiple times dataFrame.withColumnRenamed()
?
An example would be if I want to detect changes (using full outer join). Then I'm left with two DataFrame
s with the same structure.
I suggest to use the select() method to perform this. In fact withColumnRenamed() method uses select() by itself. Here is example how to rename multiple columns:
import org.apache.spark.sql.functions._
val someDataframe: DataFrame = ...
val initialColumnNames = Seq("a", "b", "c")
val renamedColumns = initialColumnNames.map(name => col(name).as(s"renamed_$name"))
someDataframe.select(renamedColumns : _*)
I think this method can help you.
public static Dataset<Row> renameDataFrame(Dataset<Row> dataset) {
for (String column : dataset.columns()) {
dataset = dataset.withColumnRenamed(column, SystemUtils.underscoreToCamelCase(column));
}
return dataset;
}
public static String underscoreToCamelCase(String underscoreName) {
StringBuilder result = new StringBuilder();
if (underscoreName != null && underscoreName.length() > 0) {
boolean flag = false;
for (int i = 0; i < underscoreName.length(); i++) {
char ch = underscoreName.charAt(i);
if ("_".charAt(0) == ch) {
flag = true;
} else {
if (flag) {
result.append(Character.toUpperCase(ch));
flag = false;
} else {
result.append(ch);
}
}
}
}
return result.toString();
}
I heve just found the answer
df1_r = df1.select(*(col(x).alias(x + '_df1') for x in df1.columns))
at stackoverflow here (see the end of the accepted answer)
or (a <- 0 to newsales.columns.length - 1)
{
var new_c = newsales.columns(a).replace('(','_').replace(')',' ').trim
newsales_var = newsales.withColumnRenamed(newsales.columns(a),new_c)
}
Although it does not answer your question directly, but I always update column names one by one. Since it updates only DF metadata, there is no harm (no performance impact) on updating column names one by one, eg:
for c in DF.columns:
new_c = c.strip().replace(' ','_')
DF = DF.withColumnRenamed(c, new_c)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.