【问题标题】:spark scala dataframe adding 1 to all the values in a columnspark scala数据框将1添加到列中的所有值
【发布时间】:2018-09-10 13:10:40
【问题描述】:

我是 spark 数据框的新手。我有一个包含类似数据的文本文件

schoolid,classid,studentid,subject,marks
bjs,5,111,hindi,23
bjs,5,222,maths,78
bjs,7,333,bio,89
bjs,1,444,chemistry,67
ghs,2,555,bio,78
ghs,2,666,phy,56
ghs,9,777,drawing,56

我想将此数据转换为数据框,并将标记列下的每个值加 1

所以我使用的代码是

val df = sparkSession.read.format("csv").option("header","true").load("samplefile1.txt")
 val newdf = df.select(col($"marks"+1)).show()

但我得到的错误是

type mismatch; found : org.apache.spark.sql.Column required: String

我可以帮助我了解正确的语法

【问题讨论】:

    标签: scala apache-spark dataframe


    【解决方案1】:

    试试这个解决方案:

    df.withColumn("marks",col("marks") + lit(1)).show
    

    【讨论】:

      【解决方案2】:
       df.withColumn("marks", expr("marks +1").cast("integer")).show
      

      输出:

      +--------+-------+---------+---------+-----+
      |schoolid|classid|studentid|  subject|marks|
      +--------+-------+---------+---------+-----+
      |     bjs|      5|      111|    hindi|   24|
      |     bjs|      5|      222|    maths|   79|
      |     bjs|      7|      333|      bio|   90|
      |     bjs|      1|      444|chemistry|   68|
      |     ghs|      2|      555|      bio|   79|
      |     ghs|      2|      666|      phy|   57|
      |     ghs|      9|      777|  drawing|   57|
      +--------+-------+---------+---------+-----+
      

      【讨论】:

        猜你喜欢
        • 2020-02-12
        • 1970-01-01
        • 2017-03-03
        • 2017-06-16
        • 1970-01-01
        • 2022-01-26
        • 2021-12-07
        • 2018-05-10
        • 1970-01-01
        相关资源
        最近更新 更多