python - 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 获得所需的结果
解决方案
由于您没有引用数据框的变量,因此最简单的方法是使用字符串条件:
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)
推荐阅读
- c# - 无法从未打开的数据库创建命令
- java - 制作签名的apk时无法恢复密钥
- c# - 使用 CefSharp 显示本地 PDF 文件
- c# - 访问请求标头 AngularJS 和 c#
- node.js - 哪种扩展 nodejs 应用程序的方式更好?
- rest - 命令需要以管理员权限 Ejabberd Rest Api 运行?
- rest - 我们如何通过 PHP Curl 使用 JIRA rest attachments api 附加多个图像?
- c# - 刷新页面以显示当前时间的统计信息
- c++ - 如何从 C++ 中分配的枚举中获取随机值?
- windows - 在同一个 shell Windows 中执行多个命令