PySpark中的比较运算符(不等于/!=)

Hen*_*k F 11 sql null apache-spark apache-spark-sql pyspark

我试图获取数据帧中的所有行,其中两个标志设置为'1',然后所有那些只有两个中的一个设置为'1'而另一个NOT EQUAL设置为'1'的行

使用以下架构(三列),

df = sqlContext.createDataFrame([('a',1,'null'),('b',1,1),('c',1,'null'),('d','null',1),('e',1,1)], #,('f',1,'NaN'),('g','bla',1)],
                            schema=('id', 'foo', 'bar')
                            )
Run Code Online (Sandbox Code Playgroud)

我获得以下数据帧:

+---+----+----+
| id| foo| bar|
+---+----+----+
|  a|   1|null|
|  b|   1|   1|
|  c|   1|null|
|  d|null|   1|
|  e|   1|   1|
+---+----+----+
Run Code Online (Sandbox Code Playgroud)

当我应用所需的过滤器时,第一个过滤器(foo = 1 AND bar = 1)起作用,但不起作用(foo = 1 AND NOT bar = 1)

foobar_df = df.filter( (df.foo==1) & (df.bar==1) )
Run Code Online (Sandbox Code Playgroud)

收益率:

+---+---+---+
| id|foo|bar|
+---+---+---+
|  b|  1|  1|
|  e|  1|  1|
+---+---+---+
Run Code Online (Sandbox Code Playgroud)

这是非行为过滤器:

foo_df = df.filter( (df.foo==1) & (df.bar!=1) )
foo_df.show()
+---+---+---+
| id|foo|bar|
+---+---+---+
+---+---+---+
Run Code Online (Sandbox Code Playgroud)

为什么不过滤?如何才能获得只有foo等于'1'的列?

joh*_*hun 13

要过滤空值,请尝试:

foo_df = df.filter( (df.foo==1) & (df.bar.isNull()) )

https://spark.apache.org/docs/1.6.2/api/python/pyspark.sql.html#pyspark.sql.Column.isNull


zer*_*323 13

为什么不过滤

因为它是SQL并NULL指示缺少值.因为任何比较NULL,除了IS NULLIS NOT NULL未定义.你需要:

col("bar").isNull() | (col("bar") != 1)
Run Code Online (Sandbox Code Playgroud)

要么

coalesce(col("bar") != 1, lit(True))
Run Code Online (Sandbox Code Playgroud)

或(PySpark> = 2.3):

col("bar").eqNullSafe(1)
Run Code Online (Sandbox Code Playgroud)

如果你想在PySpark中进行空安全比较.

'null'没有引入有效的办法NULL文字.您应该None用来指示丢失的对象.

from pyspark.sql.functions import col, coalesce, lit

df = spark.createDataFrame([
    ('a', 1, 1), ('a',1, None), ('b', 1, 1),
    ('c' ,1, None), ('d', None, 1),('e', 1, 1)
]).toDF('id', 'foo', 'bar')

df.where((col("foo") == 1) & (col("bar").isNull() | (col("bar") != 1))).show()

## +---+---+----+
## | id|foo| bar|
## +---+---+----+
## |  a|  1|null|
## |  c|  1|null|
## +---+---+----+

df.where((col("foo") == 1) & coalesce(col("bar") != 1, lit(True))).show()

## +---+---+----+
## | id|foo| bar|
## +---+---+----+
## |  a|  1|null|
## |  c|  1|null|
## +---+---+----+
Run Code Online (Sandbox Code Playgroud)