gpt4 book ai didi

string - PySpark:搜索文本和子集数据框中的子字符串

转载 作者:行者123 更新时间:2023-12-02 05:41:38 26 4
gpt4 key购买 nike

我是 pyspark 的新手,希望将现有的 pandas/python 代码转换为 PySpark

我想对我的 dataframe 进行子集化,以便仅返回包含我在 'original_problem' 字段中查找的特定关键字的行。

下面是我在 PySpark 中尝试的 Python 代码:

def pilot_discrep(input_file):

df = input_file

searchfor = ['cat', 'dog', 'frog', 'fleece']

df = df[df['original_problem'].str.contains('|'.join(searchfor))]

return df

当我尝试运行上述代码时,出现以下错误:

AnalysisException: u"Can't extract value from original_problem#207: need struct type but got string;"

最佳答案

在 pyspark 中,尝试以下操作:

df = df[df['original_problem'].rlike('|'.join(searchfor))]

或者等效的:

import pyspark.sql.functions as F
df.where(F.col('original_problem').rlike('|'.join(searchfor)))

或者,您可以选择udf:

import pyspark.sql.functions as F

searchfor = ['cat', 'dog', 'frog', 'fleece']
check_udf = F.udf(lambda x: x if x in searchfor else 'Not_present')

df = df.withColumn('check_presence', check_udf(F.col('original_problem')))
df = df.filter(df.check_presence != 'Not_present').drop('check_presence')

但是 DataFrame 方法是首选,因为它们更快。

关于string - PySpark:搜索文本和子集数据框中的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50414316/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com