Scala:如何使用Scala替换Dataframs中的值 [英] Scala: How can I replace value in Dataframs using scala

查看:1568
本文介绍了Scala:如何使用Scala替换Dataframs中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我想将列中的所有等于0.2的数字替换为0.如何在Scala中执行此操作?感谢



修改

 年|做|模型|评论|空白| 
| 2012 |特斯拉| S |没有评论| |
| 1997 |福特| E350 |现在就去找一个... | |
| 2015 |雪佛兰| Volt | null | null |

这是我的Dataframe我试图将make列中的Tesla更改为S

解决方案

注意:
由Olivier Girardot提及,这个答案没有被优化, withColumn 解决方案是使用(Azeroth2b答案)



无法删除此答案,因为它已被接受






这是我对这个的看法:

  val rdd = sc.parallelize(
List((2012,特斯拉,S),(1997,福特,E350),(2015年,雪佛兰, ))

val sqlContext = new SQLContext(sc)

//这用于将RDD隐式转换为DataFrame。
import sqlContext.implicits._

val dataframe = rdd.toDF()

dataframe.foreach(println)

dataframe。 map(row => {
val row1 = row.getAs [String](1)
val make = if(row1.toLowerCase ==tesla)Selse row1
row(row(0),make,row(2))
})。collect()。foreach(println)

// [2012,S,S]
// [1997,Ford,E350]
// [2015,Chevy,Volt]

您可以直接在 DataFrame 上直接使用 map



所以你基本上检查字符串 tesla 的列1。
如果它是 tesla ,请使用 S 的值 make else你现在的列1的值



然后使用索引(从零开始)(),使用行中的所有数据构建一个元组,我的例子中的行(行(0),make,row(2))



可能有更好的方法。我不太熟悉火花伞


For example I want to replace all numbers equal to 0.2 in a column to 0. How can I do that in Scala? Thanks

Edit:

|year| make|model| comment            |blank|
|2012|Tesla| S   | No comment         |     | 
|1997| Ford| E350|Go get one now th...|     | 
|2015|Chevy| Volt| null               | null| 

This is my Dataframe I'm trying to change Tesla in make column to S

解决方案

Note: As mentionned by Olivier Girardot, this answer is not optimized and the withColumn solution is the one to use (Azeroth2b answer)

Can not delete this answer as it has been accepted


Here is my take on this one:

 val rdd = sc.parallelize(
      List( (2012,"Tesla","S"), (1997,"Ford","E350"), (2015,"Chevy","Volt"))
  )
  val sqlContext = new SQLContext(sc)

  // this is used to implicitly convert an RDD to a DataFrame.
  import sqlContext.implicits._

  val dataframe = rdd.toDF()

  dataframe.foreach(println)

 dataframe.map(row => {
    val row1 = row.getAs[String](1)
    val make = if (row1.toLowerCase == "tesla") "S" else row1
    Row(row(0),make,row(2))
  }).collect().foreach(println)

//[2012,S,S]
//[1997,Ford,E350]
//[2015,Chevy,Volt]

You can actually use directly map on the DataFrame.

So you basically check the column 1 for the String tesla. If it's tesla, use the value S for make else you the current value of column 1

Then build a tuple with all data from the row using the indexes (zero based) (Row(row(0),make,row(2))) in my example)

There is probably a better way to do it. I am not that familiar yet with the Spark umbrella

这篇关于Scala:如何使用Scala替换Dataframs中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆