问题
String[] col = {"a","b","c"}
Data:
id a b c d e
101 1 1 1 1 1
102 2 2 2 2 2
103 3 3 3 3 3
Expected output:- id with sum of columns specified in column string
id (a+b+c)
101 3
102 6
103 9
How to do this using dataframes?
回答1:
if you are using java
you can do the following
import org.apache.spark.SparkConf;
import org.apache.spark.SparkContext;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SQLContext;
import org.apache.spark.sql.types.DataTypes;
static SparkConf conf = new SparkConf().setMaster("local").setAppName("simple");
static SparkContext sc = new SparkContext(conf);
static SQLContext sqlContext = new SQLContext(sc);
public static void main(String[] args) {
Dataset<Row> df = sqlContext.read()
.format("com.databricks.spark.csv")
.option("delimiter", " ")
.option("header", true)
.option("inferSchema", true)
.load("path to the input text file");
sqlContext.udf().register("sums", (Integer a, Integer b, Integer c) -> a+b+c, DataTypes.IntegerType);
df.registerTempTable("temp");
sqlContext.sql("SELECT id, sums(a, b, c) AS `(a+b+c)` FROM temp").show(false);
}
and you should have output as
+---+-------+
|id |(a+b+c)|
+---+-------+
|101|3 |
|102|6 |
|103|9 |
+---+-------+
If you prefer to go without sql query and use api then you can do as below
import org.apache.spark.sql.expressions.UserDefinedFunction;
import org.apache.spark.sql.types.DataTypes;
import static org.apache.spark.sql.functions.col;
import static org.apache.spark.sql.functions.udf;
UserDefinedFunction mode = udf((Integer a, Integer b, Integer c) -> a+b+c, DataTypes.IntegerType);
df.select(col("id"), mode.apply(col("a"), col("b"), col("c")).as("(a+b+c)")).show(false);
回答2:
You can create a string with the expression and then use expr
to create the column. In other words, in this case you want to create the string "a+b+c" which you then can use. This will work for any number of columns.
In Scala it can look as follows (it should be fairly simple to translate to Java):
import org.apache.spark.sql.functions.expr
val df = Seq((101,1,1,1,1,1),(102,2,2,2,2,2),(103,3,3,3,3,3)).toDF("id", "a", "b", "c", "d", "e")
val cols = Seq("a", "b", "c")
val expression = cols.mkString("+")
val colName = "(" + expression + ")"
df.select($"id", expr(expression).as(colName))
which will give you:
+---+-------+
| id|(a+b+c)|
+---+-------+
|101| 3|
|102| 6|
|103| 9|
+---+-------+
回答3:
There are many different ways to do this. You might use a map
, like this:
val df = Seq((101,1,1,1,1,1),(102,2,2,2,2,2),(103,3,3,3,3,3)).toDF("id", "a", "b", "c", "d", "e")
df.map(row => (row.getString(0), row.getInt(1)+row.getInt(2)+row.getInt(3)))
.toDF("id", "a+b+c")
Or you could use a udf
, like this:
import org.apache.spark.sql.functions._
import spark.implicits._
val addCols = udf((a: Int, b:Int, c: Int) => a+b+c)
df.select('id, addCols('a, 'b, 'c) as "a+b+c")
Or go with Shaido's suggestion :)
回答4:
This works for me in Java:
final var allDataFamilyDf = allDataDf.withColumn("FamilySize",
functions.col("SibSp").plus(functions.col("Parch")));
回答5:
A more cleaner Java way of doing this (as mentioned by @shaido-reinstate-monica):
String[] columnNames = {"a","b","c"}; // columnNames is the list of column names to be added together
Buffer<Column> sums = JavaConversions.asScalaBuffer(ImmutableList.of(columnNames).stream().map(name -> col(name)).collect(Collectors.toList()));
String expression = sums.mkString("+");
df.selectExpr("id", expression); // where df is the dataset with columns "id", "a", "b", and "c"
来源:https://stackoverflow.com/questions/50248228/summing-n-columns-in-spark-in-java-using-dataframes