基于字符串列表筛选pyspark数据帧

2024-09-23 06:30:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Pypark很陌生。我希望我能在这里得到答案。我需要一个使用DataFrameAPI的答案

我的问题是查找文本文件test.txt中包含单词“testA”或“testB”或“testC”的行数

lines=spark.read.text("C:\test.txt")
listStr=["testA","testB","testC"]

lines.filter(lines.isin(listStr)).count()  --> this is showing all the lines in the textfile

附言:如果可以用“lambda”来解决,那就更好了


Tags: the答案testtxt单词sparklines文本文件
3条回答

要从列表中查找包含一个字符串的所有行,可以使用方法^{}。例如:

+     +
|     value|
+     +
|      text|
|text testA|
|text testB|
|text testC|
|      text|
+     +

listStr=["testA","testB","testC"]
lines.filter(F.col('value').rlike('|'.join(listStr))).show()

输出:

+     +
|     value|
+     +
|text testA|
|text testB|
|text testC|
+     +

您的解决方案不起作用,因为方法^{}测试单元格值是否等于列表中的一个值。您只能对列对象(在PySpark 3中)使用此方法,否则将得到AttributeError。它将适用于以下数据帧:

+  -+
|value|
+  -+
| text|
|testA|
|testB|
|testC|
| text|
+  -+

listStr=["testA","testB","testC"]
lines.filter(F.col('value').isin(*listStr)).show()

输出:

+  -+
|value|
+  -+
|testA|
|testB|
|testC|
+  -+

您还可以使用like

from functools import reduce

df.filter(
    reduce(lambda a, b: a | b, [F.col("value").like(f"%{word}%") for word in listStr])
).count()

如果要使用lambda函数,可以使用RDD:

lines.rdd.filter(lambda r: any(s in r[0] for s in listStr)).count()

相关问题 更多 >