前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >spark dataframe新增列的处理

spark dataframe新增列的处理

作者头像
sparkexpert
发布2022-05-07 14:26:44
7620
发布2022-05-07 14:26:44
举报

往一个dataframe新增某个列是很常见的事情。

然而这个资料还是不多,很多都需要很多变换。而且一些字段可能还不太好添加。

不过由于这回需要增加的列非常简单,倒也没有必要再用UDF函数去修改列。

利用withColumn函数就能实现对dataframe中列的添加。但是由于withColumn这个函数中的第二个参数col必须为原有的某一列。所以默认先选择了个ID。

scala> val df = sqlContext.range(0, 10) df: org.apache.spark.sql.DataFrame = [id: bigint] scala> df.show() +---+ | id| +---+ |  0| |  1| |  2| |  3| |  4| |  5| |  6| |  7| |  8| |  9| +---+ scala> df.withColumn("bb",col(id)*0) <console>:28: error: not found: value id               df.withColumn("bb",col(id)*0)                                      ^ scala> df.withColumn("bb",col("id")*0) res2: org.apache.spark.sql.DataFrame = [id: bigint, bb: bigint] scala> df.show() +---+ | id| +---+ |  0| |  1| |  2| |  3| |  4| |  5| |  6| |  7| |  8| |  9| +---+ scala> res2.show() +---+---+ | id| bb| +---+---+ |  0|  0| |  1|  0| |  2|  0| |  3|  0| |  4|  0| |  5|  0| |  6|  0| |  7|  0| |  8|  0| |  9|  0| +---+---+ scala> res2.withColumn("cc",col("id")*0) res5: org.apache.spark.sql.DataFrame = [id: bigint, bb: bigint, cc: bigint] scala> res3.show() <console>:30: error: value show is not a member of Unit               res3.show()                    ^ scala> res5.show() +---+---+---+ | id| bb| cc| +---+---+---+ |  0|  0|  0| |  1|  0|  0| |  2|  0|  0| |  3|  0|  0| |  4|  0|  0| |  5|  0|  0| |  6|  0|  0| |  7|  0|  0| |  8|  0|  0| |  9|  0|  0| +---+---+---+ scala> 

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-03-31,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档