【问题标题】:Pyspark dataframe filter OR conditionPyspark 数据框过滤器或条件
【发布时间】:2019-09-02 02:34:17
【问题描述】:

我正在尝试根据 OR 条件过滤我的 pyspark 数据帧,如下所示:

filtered_df = file_df.filter(file_df.dst_name == "ntp.obspm.fr").filter(file_df.fw == "4940" | file_df.fw == "4960")

我只想返回 file_df.fw == "4940" OR file_df.fw == "4960" 的行 但是,当我尝试这个时,我得到了这个错误:

Py4JError: An error occurred while calling o157.or. Trace:
py4j.Py4JException: Method or([class java.lang.String]) does not exist

我做错了什么?

如果没有 OR 条件,当我尝试仅过滤一个条件时它会起作用 (file_df.fw=="4940")

【问题讨论】:

    标签: python dataframe pyspark conditional-statements


    【解决方案1】:

    错误信息是由操作者的优先级不同引起的。 | (OR) 作为比较运算符== 具有更高的优先级。 Spark 尝试在
    "4940"file_df.fw 上应用 OR,而不是像您想要的那样在 (file_df.fw == "4940")(file_df.fw == "4960") 上应用 OR。您可以使用方括号更改优先级。看看下面的例子:

    columns = ['dst_name','fw']
    
    file_df=spark.createDataFrame([('ntp.obspm.fr','3000'),
                                   ('ntp.obspm.fr','4940'),
                                   ('ntp.obspm.fr','4960'),
                                   ('ntp.obspm.de', '4940' )],
                                  columns)
    
    #here I have added the brackets
    filtered_df = file_df.filter(file_df.dst_name == "ntp.obspm.fr").filter((file_df.fw == "4940") | (file_df.fw == "4960"))
    filtered_df.show()
    

    输出:

    +------------+----+ 
    |    dst_name|  fw| 
    +------------+----+ 
    |ntp.obspm.fr|4940| 
    |ntp.obspm.fr|4960| 
    +------------+----+
    

    【讨论】:

      猜你喜欢
      • 2017-03-18
      • 2021-05-02
      • 2018-08-24
      • 1970-01-01
      • 1970-01-01
      • 2019-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多