【发布时间】:2021-05-28 22:29:50
【问题描述】:
对于我的df 的Text 列中的每一行,我想要执行以下操作:
-
突出显示关键字
gross,suck,singing&ponzi -
统计每行中的关键字数量并将它们存储在
Count列中
import pandas as pd
data = {'Text': ['The bread tastes good','Tuna is gross','Teddy is a beach bum','Angela suck at singing!','oneCoin was a ponzi scheme'],
'ID': [1001,1002,1003,1004,1005]
}
df = pd.DataFrame(data, columns = ['ID', 'Text'])
print(df)
所需的输出应包括 Count 列,如下所示:
我的尝试(不是最好的!你可以忽略这个):
# keyword list
key_words = ['gross','suck','singing','ponzi']
# highlight the keywords
df['Text'].applymap(lambda x: "background-color: yellow" if x else "")
# count the keywords present in each row
df['Count'] = df['Text'].str.count(r"\b(?:{})\b".format("|".join(key_words)))
高度赞赏所有尝试!
【问题讨论】:
-
df['Count'] = df['Text'].str.count(r"\b(?:{})\b".format("|".join(key_words)))? -
@WiktorStribiżew- 谢谢,这部分工作正常!标记
key_words怎么样? -
您需要在哪里突出显示它们?在 Linux 终端中?在 Jupyter 笔记本中?
-
@WiktorStribiżew,Jupyter 笔记本还是导出为 csv 文件?