使用无值过滤Pyspark数据框列

时间:2016-05-16 20:31:12

标签: python apache-spark dataframe pyspark apache-spark-sql

我试图过滤一个None作为行值的PySpark数据帧:

df.select('dt_mvmt').distinct().collect()

[Row(dt_mvmt=u'2016-03-27'),
 Row(dt_mvmt=u'2016-03-28'),
 Row(dt_mvmt=u'2016-03-29'),
 Row(dt_mvmt=None),
 Row(dt_mvmt=u'2016-03-30'),
 Row(dt_mvmt=u'2016-03-31')]

我可以使用字符串值正确过滤:

df[df.dt_mvmt == '2016-03-31']
# some results here

但这失败了:

df[df.dt_mvmt == None].count()
0
df[df.dt_mvmt != None].count()
0

但每个类别肯定都有值。发生了什么事?

11 个答案:

答案 0 :(得分:122)

您可以使用Column.isNull / Column.isNotNull

df.where(col("dt_mvmt").isNull())

df.where(col("dt_mvmt").isNotNull())

如果您只想删除NULL值,可以将na.dropsubset参数一起使用:

df.na.drop(subset=["dt_mvmt"])

NULL进行基于平等的比较不会起作用,因为在SQL NULL中未定义,因此任何将其与另一个值进行比较的尝试都会返回NULL

sqlContext.sql("SELECT NULL = NULL").show()
## +-------------+
## |(NULL = NULL)|
## +-------------+
## |         null|
## +-------------+


sqlContext.sql("SELECT NULL != NULL").show()
## +-------------------+
## |(NOT (NULL = NULL))|
## +-------------------+
## |               null|
## +-------------------+

将值与NULL进行比较的唯一有效方法是IS / IS NOT,它等同于isNull / isNotNull方法调用。

答案 1 :(得分:20)

尝试使用isNotNull功能。

<table class="table table-bordered table-striped table-hover">
    <thead>
        <tr>
            <th><input type="checkbox" id="allcb" name="allcb"/> Check all</th>
            <th data-field="id">ID</th>
            <th data-field="firstName">First name</th>
            <th data-field="lastName">Last name</th>
        </tr>
    </thead>
    <tbody>
        {% for user in product.users %}
                <td><input type="checkbox" name="checkBox[]"  id="ic" value="{{ user.id }}" /></td>
                <td  data-title="id">{{user.id}}</td>
                <td data-title="firstName">{{user.firstname}}</td>
                <td data-title="lastName" contenteditable='true' name="v1">{{user.lastname}}</td>

            </tr>
        {% endfor %}
    </tbody>

</table>
if(isset($_POST['checkBox']) && !empty($_POST['checkBox'])&& isset($_POST['v1'])){

         $user =$_POST['checkBox'];
        $v1 =$_POST['v1'];

         $zl = 0;
         foreach ($user  as $id)
         {
           foreach ($v1 as $v2)
           {

             $userd = $em->getRepository('UserBundle:User')->find($id);
             $userd->setlastName($v2);
             $em->persist($userd);


             ++$zl;
           }}

        $em->flush();
      }

答案 2 :(得分:9)

要获取dt_mvmt列中的值不为空的条目,我们有

df.filter("dt_mvmt is not NULL")

对于null的条目,我们有

df.filter("dt_mvmt is NULL")

答案 3 :(得分:2)

您可以通过多种方式从DataFrame的列中删除/过滤空值。

让我们使用以下代码创建一个简单的DataFrame:

date = ['2016-03-27','2016-03-28','2016-03-29', None, '2016-03-30','2016-03-31']
df = spark.createDataFrame(date, StringType())

现在,您可以尝试以下方法之一来过滤出空值。

# Approach - 1
df.filter("value is not null").show()

# Approach - 2
df.filter(col("value").isNotNull()).show()

# Approach - 3
df.filter(df["value"].isNotNull()).show()

# Approach - 4
df.filter(df.value.isNotNull()).show()

# Approach - 5
df.na.drop(subset=["value"]).show()

# Approach - 6
df.dropna(subset=["value"]).show()

# Note: You can also use where function instead of a filter.

您还可以查看blog上的“使用NULL值”部分以了解更多信息。

我希望这会有所帮助。

答案 4 :(得分:1)

如果列=无

COLUMN_OLD_VALUE
----------------
None
1
None
100
20
------------------

使用 在数据框上创建一个临时表:

sqlContext.sql("select * from tempTable where column_old_value='None' ").show()

因此请使用:column_old_value='None'

答案 5 :(得分:1)

如果您想保留Pandas语法,这对我有用。

df = df[df.dt_mvmt.isNotNull()]

答案 6 :(得分:0)

PySpark根据算术,逻辑和其他条件提供各种过滤选项。 NULL值的存在可能会妨碍进一步的处理。删除它们或从统计学上估算它们可能是一种选择。

可以考虑以下代码集:

# Dataset is df
# Column name is dt_mvmt
# Before filtering make sure you have the right count of the dataset
df.count() # Some number

# Filter here
df = df.filter(df.dt_mvmt.isNotNull())

# Check the count to ensure there are NULL values present (This is important when dealing with large dataset)
df.count() # Count should be reduced if NULL values are present

答案 7 :(得分:0)

我也会尝试:

$count = $dbh->do("SELECT COUNT(*) from ( SELECT column1 from table )"); if($count>1) do X; else do Y;

答案 8 :(得分:0)

如果要过滤出列中没有值的记录,请参见以下示例:

df=spark.createDataFrame([[123,"abc"],[234,"fre"],[345,None]],["a","b"])

现在过滤掉空值记录:

df=df.filter(df.b.isNotNull())

df.show()

如果要从DF中删除这些记录,请参见以下内容:

df1=df.na.drop(subset=['b'])

df1.show()

答案 9 :(得分:0)

None / Null是pyspark / python中类NoneType的数据类型 因此,当您尝试将NoneType对象与字符串对象进行比较时,下面的方法将不起作用

错误的过滤方法

df [df.dt_mvmt == None] .count() 0 df [df.dt_mvmt!= None] .count() 0

正确

df = df.where(col(“ dt_mvmt”)。isNotNull()) 返回所有记录,其中dt_mvmt为None / Null

答案 10 :(得分:0)

isNull()/ isNotNull()将返回dt_mvmt为Null或!Null的相应行。

method_1 = df.filter(df['dt_mvmt'].isNotNull()).count()
method_2 = df.filter(df.dt_mvmt.isNotNull()).count()

两者都会返回相同的结果

相关问题