我怎样才能通过在数据帧取代空号? [英] How can I replace numbers by nulls in a DataFrame?

查看:215
本文介绍了我怎样才能通过在数据帧取代空号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是陌生的,但我想知道如何更换任意数量的整体数据帧使用斯卡拉

It might be strange, but I was wondering how to replace any number of a whole DataFrame's Column for null using Scala.

想象一下,我有一个可为空 DoubleType 指定的列山坳。在那里,我想通过替换为(1.0〜10.0)不同的所有数字是

Imagine I have a nullable DoubleType column named col. There, I want to replace all numbers different to (1.0 ~ 10.0) by a null.

我试过欠佳下一个code。

I tried unsatisfactorily the next code.

val xf = df.na.replace("col", Map(0.0 -> null.asInstanceOf[Double]).toMap)

但是,正如你在斯卡拉实现当你转换成为psented为 0.0 重新$ p $,这不是我想要的。此外,我无法实现任何方式与值的范围来做到这一点。因此,我想,如果有任何的方式来实现这一目标?

But, as you realize in Scala when you convert a null into a Double it becomes represented as a 0.0, and this is not what I want. Besides, I can't realize any way to do it with a range of values. Therefore, I am thinking if there is any way to achieve this?

推荐答案

如何而不是条款?

import org.apache.spark.sql.functions.when

val df = sc.parallelize(
  (1L, 0.0) :: (2L, 3.6) :: (3L, 12.0) :: (4L, 5.0) ::  Nil
).toDF("id", "val")

df.withColumn("val", when($"val".between(1.0, 10.0), $"val")).show

// +---+----+
// | id| val|
// +---+----+
// |  1|null|
// |  2| 3.6|
// |  3|null|
// |  4| 5.0|
// +---+----+

不满足的predicate任何值(这里是 VAL 1.0〜10.0 )将被替换为 NULL

又见创建空/空字段值新的数据框

这篇关于我怎样才能通过在数据帧取代空号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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