首页 > 解决方案 > pyspark 数据框“条件应该是字符串或列”

问题描述

我无法在数据框上使用过滤器。我不断收到错误“TypeError(”条件应该是字符串或列“)”

我尝试将过滤器更改为使用 col 对象。尽管如此,它还是行不通。

path = 'dbfs:/FileStore/tables/TravelData.txt'
data = spark.read.text(path)
from pyspark.sql.types import StructType, StructField, IntegerType , StringType, DoubleType
schema = StructType([
  StructField("fromLocation", StringType(), True),
  StructField("toLocation", StringType(), True),
  StructField("productType", IntegerType(), True)
])
df = spark.read.option("delimiter", "\t").csv(path, header=False, schema=schema)
from pyspark.sql.functions import col
answerthree = df.select("toLocation").groupBy("toLocation").count().sort("count", ascending=False).take(10)  # works fine
display(answerthree)

我向变量“answerthree”添加了一个过滤器,如下所示:

answerthree = df.select("toLocation").groupBy("toLocation").count().filter(col("productType")==1).sort("count", ascending=False).take(10)

它抛出错误如下:“”无法解析' productType'给定输入列“”条件应该是字符串或列“

在 jist 中,我正在尝试使用 pyspark 而不是 scal 来解决以下链接中给出的问题 3。下面的 url 中还提供了数据集。 https://acadgild.com/blog/spark-use-case-travel-data-analysis?fbclid=IwAR0fgLr-8aHVBsSO_yWNzeyh7CoiGraFEGddahDmDixic6wmumFwUlLgQ2c

我应该只能为 productType 值 1 获得所需的结果

标签: pythondataframefilterpyspark

解决方案


由于您没有引用数据框的变量,因此最简单的方法是使用字符串条件:

answerthree = df.select("toLocation").groupBy("toLocation").count()\
                .filter("productType = 1")\
                .sort(...

或者,您可以使用数据框变量并使用基于列的过滤器:

count_df = df.select("toLocation").groupBy("toLocation").count()
answerthree = count_df.filter(count_df['productType'] == 1)\
                      .sort("count", ascending=False).take(10)

推荐阅读