首页 > 解决方案 > PySpark - 无法按另一列的值过滤行

问题描述

我一直试图让这个简单的代码工作,但到目前为止还没有运气。

df = sqlContext.createDataFrame([
    ('www.example.com/researc', 'Research Reports'),
    ('www.example.com/careers', 'Careers'),
    ('www.example.com/blogs', 'blogs'),
    ('www.example.com', None),
    ('www.example.com/navigation', None),
    ('www.example.com', 'main'),
    ('www.example.jp', None),
    ('', 'blogs')], ['A', 'B'])

display(df.toPandas())
df.printSchema()
print('Original DF')
display(df.toPandas())

filter_mask = df.where(df['B'].isNotNull())
print("\n\nFilter Mask")
display(filter_mask.toPandas())

print('\n\nfilter_mask[A]')
filter_mask.select('A').show()

# Why is "response" returning everything?!
response = df.filter(df['A'].isin(filter_mask['A']))
print("\n\nResulting DF")
display(response.toPandas())

我试图从'B'中过滤掉所有空值,然后只保留A中的所有相应值;但是我的逻辑继续返回整个数据框。有人可以帮我弄清楚为什么我没有正确过滤这些值吗?

更新

所以我想要的输出是:

+--------------------+----------------+
|                   A|               B|
+--------------------+----------------+
|www.example.com/r...|Research Reports|
|www.example.com/c...|         Careers|
|www.example.com/b...|           blogs|
|     www.example.com|            null|
|     www.example.com|            main|
|                    |           blogs|
+--------------------+----------------+

^ 基本上,我想保留所有映射到 B 中任何非空值的 URL。(因此对于“www.example.com”,即使其中一个映射为空,因为它的另一个实例没有映射为null;它仍然在最终结果中返回。

标签: pyspark

解决方案


df.filter(df.B.isNotNull()).show()

推荐阅读