【发布时间】:2017-06-20 23:04:01
【问题描述】:
我在 Spark 中有以下数据框和架构
val df = spark.read.options(Map("header"-> "true")).csv("path")
scala> df show()
+-------+-------+-----+
| user| topic| hits|
+-------+-------+-----+
| om| scala| 120|
| daniel| spark| 80|
|3754978| spark| 1|
+-------+-------+-----+
scala> df printSchema
root
|-- user: string (nullable = true)
|-- topic: string (nullable = true)
|-- hits: string (nullable = true)
我想将列命中数更改为整数
我试过这个:
scala> df.createOrReplaceTempView("test")
val dfNew = spark.sql("select *, cast('hist' as integer) as hist2 from test")
scala> dfNew.printSchema
root
|-- user: string (nullable = true)
|-- topic: string (nullable = true)
|-- hits: string (nullable = true)
|-- hist2: integer (nullable = true)
但是当我打印数据框时,列 hist 2 填充了 NULLS
scala> dfNew show()
+-------+-------+-----+-----+
| user| topic| hits|hist2|
+-------+-------+-----+-----+
| om| scala| 120| null|
| daniel| spark| 80| null|
|3754978| spark| 1| null|
+-------+-------+-----+-----+
我也试过这个:
scala> val df2 = df.withColumn("hitsTmp",
df.hits.cast(IntegerType)).drop("hits"
).withColumnRenamed("hitsTmp", "hits")
得到了这个:
<console>:26: error: value hits is not a member of org.apache.spark.sql.DataFram
e
也试过这个:
scala> val df2 = df.selectExpr ("user","topic","cast(hits as int) hits")
and got this:
org.apache.spark.sql.AnalysisException: cannot resolve '`topic`' given input col
umns: [user, topic, hits]; line 1 pos 0;
'Project [user#0, 'topic, cast('hits as int) AS hits#22]
+- Relation[user#0, topic#1, hits#2] csv
与
scala> val df2 = df.selectExpr ("cast(hits as int) hits")
我收到类似的错误。
任何帮助将不胜感激。我知道这个问题之前已经解决过,但我尝试了 3 种不同的方法(在此处发布),但都没有奏效。
谢谢。
【问题讨论】:
-
我使用的是 2.1.0 版
标签: scala casting apache-spark-sql