[英]How to apply a defined function to many rows?
我想将定义的 function “标记化”应用于数据集“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 dataframe,如果您想将 function 应用于列,请使用df["col"].apply(func)
在此示例中,要将结果添加为新列,请使用:
reviews_english["tokenized"] = reviews_english["Review Gast"].astype(str).apply(tokenization)
如果您不使用 pandas dataframe,请使用 Corralien 的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.