PySpark数据帧:过滤包含四个或更多非空列的记录

时间:2016-04-03 23:08:31

标签: python pyspark

我有许多PySpark数据帧,其中两列中的数据是必需的,其他列是可选的。必填列包含日期和记录ID;最有价值的数据位于可选列中。我试图捕获可选列中元素之间的连接。

数据帧,预过滤器:

id     col1    col2    col3    date
123            xyz             20160401
234    abc     pqr             20160401
345    def     hij     klm     20160401
456                            20160401

过滤后,数据框如下所示:

id     col1    col2    col3    date
234    abc     pqr             20160401
345    def     hij     klm     20160401

具有多个非空列值的记录很有意思,因为它们描述了关系。

我注意到PySpark有.filter方法。文档中的示例通常显示过滤列,例如df_filtered = df.filter(df.some_col > some_value)。我试图编写一个过滤器来捕获具有四个或更多任意数据帧的非空列的所有记录,即不得明确说明列名。

在PySpark中有一种简单的方法吗?

更新

虽然.dropna(thresh=4)似乎正是我正在寻找的,但出于某种原因,它并没有奏效。 E.g。

df.collect()

[Row(id=123, col1=None,         col2=None, col3=3754907743, date='20160403'),
 Row(id=124, col1=7911019393,   col2=None, col3=1456473867, date='20160403'),
 Row(id=125, col1=None,         col2=None, col3=2049622472, date='20160403'),
 Row(id=126, col1=4345043212,   col2=None, col3=3168577324, date='20160403'),
 Row(id=127, col1=None,         col2=None, col3=3185277065, date='20160403'),
 Row(id=128, col1=1336048242,   col2=None, col3=1322345860, date='20160403')]

无论thresh号是什么,它总是返回原始数据帧中的所有记录:

df_filtered = df.dropna(thresh=[any number])

df_filtered.collect()

[Row(id=123, col1=None,         col2=None, col3=3754907743, date='20160403'),
 Row(id=124, col1=7911019393,   col2=None, col3=1456473867, date='20160403'),
 Row(id=125, col1=None,         col2=None, col3=2049622472, date='20160403'),
 Row(id=126, col1=4345043212,   col2=None, col3=3168577324, date='20160403'),
 Row(id=127, col1=None,         col2=None, col3=3185277065, date='20160403'),
 Row(id=128, col1=1336048242,   col2=None, col3=1322345860, date='20160403')]

我正在运行Spark版本1.5.0-cdh5.5.2。

1 个答案:

答案 0 :(得分:1)

docs开始,您正在寻找dropna

  

dropna(how ='any',thresh = None,subset = None)

     

返回一个新的DataFrame,省略具有空值的行。   DataFrame.dropna()和DataFrameNaFunctions.drop()是每个的别名   其它.-

     

参数:

how – ‘any’ or ‘all’. If ‘any’, drop a row if it contains any nulls.
       If ‘all’, drop a row only if all its values are null.

thresh – int, default None If specified, drop rows that have less than
         thresh non-null values. This overwrites the how parameter.

subset – optional list of column names to consider.

因此,要回答您的问题,您可以尝试df.dropna(thresh=4)