开发者社区> 问答> 正文

如何删除PySpark中少于三个字母的单词?

我有一个“文本”列,其中存储了令牌数组。如何过滤所有这些数组,使令牌长度至少为三个字母?

from pyspark.sql.functions import regexp_replace, col
from pyspark.sql.session import SparkSession

spark = SparkSession.builder.getOrCreate()

columns = ['id', 'text']
vals = [

(1, ['I', 'am', 'good']),
(2, ['You', 'are', 'ok']),

]

df = spark.createDataFrame(vals, columns)
df.show()

Had tried this but have TypeError: Column is not iterable
df_clean = df.select('id', regexp_replace('text', [len(word) >= 3 for word
in col('text')], ''))
df_clean.show()
我希望看到:

id | text
1 | [good]
2 | [You, are]

展开
收起
社区小助手 2018-12-06 13:55:01 2233 0
1 条回答
写回答
取消 提交回答
  • 社区小助手是spark中国社区的管理员,我会定期更新直播回顾等资料和文章干货,还整合了大家在钉群提出的有关spark的问题及回答。

    这样做,您可以决定是否排除行,我添加了一个额外的列并过滤掉了,

    from pyspark.sql import functions as f

    columns = ['id', 'text']
    vals = [

        (1, ['I', 'am', 'good']),
        (2, ['You', 'are', 'ok']),
        (3, ['ok'])
       ]
    

    df = spark.createDataFrame(vals, columns)

    df.show()

    df2 = df.withColumn("text_left_over", f.expr("filter(text, x -> not(length(x) < 3))"))
    df2.show()

    This is the actual piece of logic you are looking for.

    df3 = df.withColumn("text_left_over", f.expr("filter(text, x -> not(length(x) < 3))")).where(f.size(f.col("text_left_over")) > 0).drop("text")
    df3.show()
    收益:

    id text text_left_over
    1 [I, am, good] [good]
    2 [You, are, ok] [You, are]
    3 [ok] []
    id text_left_over
    1 [good]
    2 [You, are]
    2019-07-17 23:18:31
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载