Scala:对于数据框上的循环,从现有索引创建新列
Scala: For loop on dataframe, create new column from existing by index
我有一个包含两列的数据框:
id (string), date (timestamp)
我想遍历数据框,并添加一个带有 url 的新列,其中包含 ID。该算法应如下所示:
add one new column with the following value:
for each id
"some url" + the value of the dataframe's id column
我试图在 Scala 中完成这项工作,但我在获取 "a"
索引上的特定 ID 时遇到问题
val k = df2.count().asInstanceOf[Int]
// for loop execution with a range
for( a <- 1 to k){
// println( "Value of a: " + a );
val dfWithFileURL = dataframe.withColumn("fileUrl", "https://someURL/" + dataframe("id")[a])
}
但是这个
dataframe("id")[a]
不使用 Scala。目前还没有找到解决方案,欢迎大家多多指教!
不确定这是否是您所需要的,但您可以使用 zipWithIndex
进行索引。
data.show()
+---+---------------+
| Id| Url|
+---+---------------+
|111|http://abc.go.org/|
|222|http://xyz.go.net/|
+---+---------------+
import org.apache.spark.sql._
val df = sqlContext.createDataFrame(
data.rdd.zipWithIndex
.map{case (r, i) => Row.fromSeq(r.toSeq:+(s"""${r.getString(1)}${i+1}"""))},
StructType(data.schema.fields :+ StructField("fileUrl", StringType, false))
)
输出:
df.show(false)
+---+---------------+----------------+
|Id |Url |fileUrl |
+---+---------------+----------------+
|111|http://abc.go.org/|http://abc.go.org/1|
|222|http://xyz.go.net/|http://xyz.go.net/2|
+---+---------------+----------------+
您可以简单地使用 Scala 中的 withColumn
函数,如下所示:
val df = Seq(
( 1, "1 Jan 2000" ),
( 2, "2 Feb 2014" ),
( 3, "3 Apr 2017" )
)
.toDF("id", "date" )
// Add the fileUrl column
val dfNew = df
.withColumn("fileUrl", concat(lit("https://someURL/"), $"id"))
.show
我的结果:
我有一个包含两列的数据框:
id (string), date (timestamp)
我想遍历数据框,并添加一个带有 url 的新列,其中包含 ID。该算法应如下所示:
add one new column with the following value:
for each id
"some url" + the value of the dataframe's id column
我试图在 Scala 中完成这项工作,但我在获取 "a"
索引上的特定 ID 时遇到问题 val k = df2.count().asInstanceOf[Int]
// for loop execution with a range
for( a <- 1 to k){
// println( "Value of a: " + a );
val dfWithFileURL = dataframe.withColumn("fileUrl", "https://someURL/" + dataframe("id")[a])
}
但是这个
dataframe("id")[a]
不使用 Scala。目前还没有找到解决方案,欢迎大家多多指教!
不确定这是否是您所需要的,但您可以使用 zipWithIndex
进行索引。
data.show()
+---+---------------+
| Id| Url|
+---+---------------+
|111|http://abc.go.org/|
|222|http://xyz.go.net/|
+---+---------------+
import org.apache.spark.sql._
val df = sqlContext.createDataFrame(
data.rdd.zipWithIndex
.map{case (r, i) => Row.fromSeq(r.toSeq:+(s"""${r.getString(1)}${i+1}"""))},
StructType(data.schema.fields :+ StructField("fileUrl", StringType, false))
)
输出:
df.show(false)
+---+---------------+----------------+
|Id |Url |fileUrl |
+---+---------------+----------------+
|111|http://abc.go.org/|http://abc.go.org/1|
|222|http://xyz.go.net/|http://xyz.go.net/2|
+---+---------------+----------------+
您可以简单地使用 Scala 中的 withColumn
函数,如下所示:
val df = Seq(
( 1, "1 Jan 2000" ),
( 2, "2 Feb 2014" ),
( 3, "3 Apr 2017" )
)
.toDF("id", "date" )
// Add the fileUrl column
val dfNew = df
.withColumn("fileUrl", concat(lit("https://someURL/"), $"id"))
.show
我的结果: