【问题标题】:How to apply a defined function to many rows?如何将定义的函数应用于多行?
【发布时间】:2021-06-04 09:28:45
【问题描述】:

我想将定义的函数“标记化”应用于数据集“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)

【问题讨论】:

    标签: python function sentiment-analysis review


    【解决方案1】:

    使用列表理解

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

    map:

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

    【讨论】:

      【解决方案2】:

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

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

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

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

      【讨论】:

      • 感谢您的回复!我应用了它 - 但是,发生了这个错误:AttributeError: 'float' object has no attribute 'replace'
      • 尝试强制数据为字符串。也许其中一条评论只是一个数字,例如五颗星的“5.0”,它被解释为一个字符串。我已使用 .astype(str) 修改了代码以执行此操作
      • 非常感谢 - 它成功了! :) 可悲的是,我不能给你任何支持,因为我几乎没有回应。
      • 没关系,很高兴听到。你可以按勾选按钮接受这个我相信的答案:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-28
      • 2023-04-10
      • 2019-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多