首页 > 解决方案 > 在 Dataframe 上使用 where() 或 filter() 时出错

问题描述

我想检查 Dataframe 列中的值first_id是否在我拥有的 python id 列表中,如果是,那么它应该通过过滤器。

first_id_list = [1,2,3,4,5,6,7,8,9]

other_ids = id_dataframe.where(ids["first_id"] in first_id_list).select("other_id")

我正在用 python 编写,id_dataframe是一个 PySpark Dataframe,first_id_list是一个 python 整数列表。

我得到的错误是:

ValueError: Cannot convert column into bool: please use '&' for 'and', '|' for 'or', '~' for 'not' when building DataFrame boolean expressions.

标签: pythonpysparkboolean-expressionpyspark-dataframes

解决方案


这个表达式有问题:ids["first_id"] in first_id_list

ids["first_id"]是一个 Pyspark 列。first_id_list是一个 Python 列表。

where()Pyspark Dataframe 方法需要一个布尔列来评估,但是你给它一个错误的 python 布尔表达式。

您必须使用 Pyspark Column 方法isin()(文档:https ://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.Column.isin )

回答 :

other_ids = id_dataframe.where(ids["first_id"].isin(first_id_list)).select("other_id")

现在ids["first_id"].isin(first_id_list)是一个返回布尔列的 DataFrame 布尔表达式。


推荐阅读