微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将定义的函数应用于多行?

如何解决如何将定义的函数应用于多行?

我想将定义的函数标记化”应用于数据集“reviews_english”的“Review Gast”列的所有行。我怎样才能做到这一点?目前我只能将它应用于一行。谢谢! :)


def tokenization(text):
    # normalize
    text = normalize(text)

    # Remove Punctuation
    text = remove_punctuation(text)

    # Tokenize
    tokens = text.split()

    # Remove Stopwords
    tokens = remove_stopwords(tokens)

    # Apply Bag-of-Words (set of tokens)
    bow = set(tokens)

    return bow

clean_reviews_english =tokenization(reviews_english["Review Gast"][0])
print(clean_reviews_english)

解决方法

使用列表理解

clean_reviews_english = tokenization(review for review in reviews_english["Review Gast"])

map

clean_reviews_english = map(tokenization,reviews_english["Review Gast"])
,

假设您使用的是 Pandas 数据框,如果您想将函数应用于列,请使用 df["col"].apply(func)

在此示例中,要将结果添加为新列,请使用:

reviews_english["tokenized"] = reviews_english["Review Gast"].astype(str).apply(tokenization)

如果您不使用 Pandas 数据框,请使用 Corralien 的答案。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。