簡體   English   中英

Scala:對於數據框上的循環,從現有索引創建新列

[英]Scala: For loop on dataframe, create new column from existing by index

我有兩列的數據框:

id(字符串),日期(時間戳)

我想遍歷數據框,並添加一個帶有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])

      }

但是這個

數據幀( “ID”)[α]

與Scala不兼容。 我還找不到解決方案,因此歡迎提出各種建議!

您可以簡單地在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

我的結果:

標量結果

不知道這是否是您所需要的,但是可以使用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|
+---+---------------+----------------+

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM