简体   繁体   English

Spark scala dataframe 获取每行的值并分配给变量

[英]Spark scala dataframe get value for each row and assign to variables

I have a dataframe like below:我有一个 dataframe 如下所示:

val df=spark.sql("select * from table") val df=spark.sql("从表中选择 *")

row1|row2|row3第 1 行|第 2 行|第 3 行

A1,B1,C1 A1,B1,C1

A2,B2,C2 A2,B2,C2

A3,B3,C3 A3,B3,C3

i want to iterate for loop to get values like this:我想迭代 for 循环以获得这样的值:

val value1="A1" val value1="A1"

val value2="B1" val value2="B1"

val value3="C1" val value3="C1"

function(value1,value2,value3)函数(值1,值2,值3)

Please help me.请帮我。

emphasized text强调文本

You have 2 options:您有 2 个选项:

  • Solution 1- Your data is big, then you must stick with dataframes.解决方案 1-您的数据很大,那么您必须坚持使用数据框。 So to apply a function on every row.因此,要在每一行上应用 function。 We must define a UDF.我们必须定义一个 UDF。

  • Solution 2- Your data is small, then you can collect the data to the driver machine and then iterate with a map.解决方案 2-您的数据很小,然后您可以将数据收集到驱动程序机器,然后使用 map 进行迭代。

Example:例子:

val df = Seq((1,2,3), (4,5,6)).toDF("a", "b", "c")
def sum(a: Int, b: Int, c: Int) = a+b+c

// Solution 1
import org.apache.spark.sql.Row
val myUDF = udf((r: Row) => sum(r.getAs[Int](0), r.getAs[Int](1), r.getAs[Int](2)))

df.select(myUDF(struct($"a", $"b", $"c")).as("sum")).show

//Solution 2
df.collect.map(r=> sum(r.getAs[Int](0), r.getAs[Int](1), r.getAs[Int](2))) 

Output for both cases: Output两种情况:

+---+
|sum|
+---+
|  6|
| 15|
+---+

EDIT:编辑:

val myUDF = udf((r: Row) => {
  val value1 = r.getAs[Int](0)
  val value2 = r.getAs[Int](1)
  val value3 = r.getAs[Int](2)

  myFunction(value1, value2, value3)
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 迭代 Stream dataframe 中的列值,并使用 Scala 和 Spark 将每个值分配给一个公共列表 - Iterate a column values in a Stream dataframe and assign each value to a common list using Scala and Spark Scala Spark 转换数据帧并从每一行获取所有唯一 ID 及其类型 - Scala Spark Convert Dataframe and get all Unique IDs and its type from each row Scala Spark数据框-每行的总和为Array [Double] - Scala Spark Dataframe - Sum for each row the content of Array[Double] 使用 scala/spark 计算数据帧列中每一行的 z 分数 - calculate the z score for each row in the column of a dataframe using scala / spark 将列表添加到 Scala/Spark 中的数据帧,以便将每个元素添加到单独的行 - Adding a list to a dataframe in Scala / Spark such that each element is added to a separate row spark scala每个数据集输出为单个数据帧行 - spark scala each datasets output as a single row of dataframe 迭代火花 dataframe 并将每一行值存储在另一个 class 的变量中 - Iterate over a spark dataframe and store each row value in variables of another class 如何在spark scala数据框中获取与某列的最小值相对应的行 - how to get the row corresponding to the minimum value of some column in spark scala dataframe #SPARK #需要从spark Scala中的其他dataframe列分配dataframe列值 - #SPARK #Need to assign dataframe column value from other dataframe column in spark Scala Scala Dataframe获取特定行的最大值 - Scala Dataframe get max value of specific row
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM