python - 如果文本包含在另一个数据框中,则使用二进制指定标记行
问题描述
我正在研究挖掘调查数据。我能够标记某些关键字的行:
survey['Rude'] = survey['Comment Text'].str.contains('rude', na=False, regex=True).astype(int)
现在,我想标记任何包含名称的行。我有另一个包含美国常见名称的数据框。这是我认为可行的方法,但它没有标记任何行,并且我已验证名称确实存在于“评论文本”中
for row in survey:
for word in survey['Comment Text']:
survey['Name'] = 0
if word in names['Name']:
survey['Name'] = 1
解决方案
您没有正确循环浏览该系列。 for row in survey:
循环遍历survey
. for word in survey['Comment Text']:
循环通过注释字符串。survey['Name'] = 0
创建一列 all 0s
。
您可以使用set intersections和apply()来避免所有循环行:
survey = pd.DataFrame({'Comment_Text':['Hi rcriii',
'Hi yourself stranger',
'say hi to Justin for me']})
names = pd.DataFrame({'Name':['rcriii', 'Justin', 'Susan', 'murgatroyd']})
s2 = set(names['Name'])
def is_there_a_name(s):
s1 = set(s.split())
if len(s1.intersection(s2))>0:
return 1
else:
return 0
survey['Name'] = survey['Comment_Text'].apply(is_there_a_name)
print(names)
print(survey)
Name
0 rcriii
1 Justin
2 Susan
3 murgatroyd
Comment_Text Name
0 Hi rcriii 1
1 Hi yourself stranger 0
2 say hi to Justin for me 1
作为奖励,返回len(s1.intersection(s2))
以获取每行的匹配数。
推荐阅读
- json - 如何在 json 文件中使用 powershell 语法?
- html - Cordova 中约 200 毫秒的触摸(点击)延迟,但在浏览器或 PWA 中没有
- node.js - 当我尝试在本地运行函数时,firebase 显示错误
- postgresql - Postgres:psql:致命:Windows 10 中不存在数据库“root”
- laravel - Laravel Mix - 如何观察多个入口点的变化
- swift - 在嵌套容器中查找后代按钮
- python - DatetimeIndex 不能执行操作的意思
- android - Android导航组件动画从活动返回到片段
- java - 在 JTable 上使用 RowSorter.SortKey 时下移空行
- android - 如何在 LinearLoyout ImageView 中设置点击监听器