python - 将每个 pandas 行与列表字典进行比较,并将新变量附加到数据框
问题描述
我想检查熊猫数据框字符串列的每一行并附加一个新列,如果在列表字典中找到文本列的任何元素,则返回 1。
例子:
# Data
df = pd.DataFrame({'id': [1, 2, 3],
'text': ['This sentence may contain reference.',
'Orange, blue cow','Does the cow operate any heavy machinery?']},
columns=['numbers', 'text'])
# Rule dictionary
rule_dict = {'rule1': ['Does', 'the'],
'rule2':['Sentence','contain'],
'rule3': ['any', 'reference', 'words']}
# List of variable names to be appended to df
rule_list = ['has_rule1','has_rule2','has_rule3']
# Current for loop
for Key in rule_dict:
for i in rule_list:
df[i] = df.text.apply(lambda x: (
1 if any(ele in x for ele in rule_dict[Key]) == 1 and (len(str(x)) >= 3)
else 0))
# Current output, looks to be returning a 1 if text is found in ANY of the lists
df = pd.DataFrame({'id': [1, 2, 3],
'text': ['This sentence may contain reference.',
'Orange, blue cow','Does the cow operate any heavy machinery?'],
'has_rule1': [1,1,1],
'has_rule2': [0,0,0],
'has_rule3': [1,1,1]},
columns=['id', 'text','has_rule1','has_rule2','has_rule3'])
# Anticipated output
df = pd.DataFrame({'id': [1, 2, 3],
'text': ['This sentence may contain reference.',
'Orange, blue cow','Does the cow operate any heavy machinery?'],
'has_rule1': [0,0,1],
'has_rule2': [1,0,0],
'has_rule3': [1,0,1]},
columns=['id', 'text','has_rule1','has_rule2','has_rule3'])
解决方案
假设您解决了评论中提到的有关 dict 理解的问题,则不应使用嵌套for
循环。相反,使用单个for
循环zip
:
for (k,v), n in zip(rule_dict.items(), rule_list):
pat = rf'\b{"|".join(v)}\b'
df[n] = df.text.str.contains(pat).astype(int)
输出:
id text has_rule1 has_rule2 has_rule3
-- ---- ----------------------------------------- ----------- ----------- -----------
0 1 This sentence may contain reference. 0 1 1
1 2 Orange, blue cow 0 0 0
2 3 Does the cow operate any heavy machinery? 1 0 1
推荐阅读
- ios - 如何在 WKWebview 中处理文件上传?
- laravel - {{Input::get('min_price')}} 不起作用。如何解决这个问题?
- java - 查找字符串中的对应元素
- c++ - 使用 boost ringbuffer 的多线程消费者不产生与输入相同的输出
- php - 函数 PendingResourceRegistration::name(),1 在第 18 行的 C:\xampp\htdocs\project\routes\web.php 中传递的参数太少,而预期的正好是 2
- javascript - 在没有 getFieldDecorator 的情况下使用带有 antd 的 react-input-mask
- amazon-web-services - 如何验证 AWS Web Identity Federation 角色中的授权?
- c# - 表格中的一切都消失了
- google-cloud-platform - Gsutil 在存储桶中创建“tmp”文件
- javascript - Firebase 不断执行对 .lp 的请求?