python - 如何从与我的字典中的“值”匹配的文本字段中提取字符串并将字典的键返回到输出中的新列中?
问题描述
我想从描述字段(我的 DF 中的列)中提取与字典中的另一个字符串匹配的第一个字符串(使用 Python),或者如果没有匹配项则显示 Null,例如:
# read an excel with columns (IDX, DESCRIPTION)
df = pd.read_excel("example.xlsx")
输入:example.xlsx
[IDX] [Column DESCRIPTION]
[Row 1] ["I live in Russia"]
[Row 2] ["I was borned in USA"]
[Row 3] ["I would like to move to England"]
我的字典有以下国家:
countries= [
{'value': ['usa'], 'country': 'United States of America'},
{'value': ['u.s.a.'], 'country': 'United States of America'},
{'value': ['united states'], 'country': 'United States of America'},
{'value': ['spain'], 'country': 'Spain'},
{'value': ['russia'], 'country': 'Russia'},
{'value': ['rusia'], 'country': 'Russia'},
{'value': ['canada'], 'country': 'Canada'},
{'value': ['france'], 'country': 'France'},
{'value': ['mexico'], 'country': 'Mexico'}
]
输出:
[IDX] [Column DESCRIPTION] [Column Country]
[Row 1] ["I live in Russia"] ['RUSSIA']
[Row 2] ["I was borned in USA"] ['UNITED STATES OF AMERICA']
[Row 3] ["I would like to move to England"] [Null]
带有匹配国家或空的附加列的新 Excel
解决方案
如果我理解你的话,你想要这样的东西:
strngs = ["I live in Russia", "I was borned in USA", "I would like to move to England"]
dictt = ["USA", "CANADA", "RUSSIA", "MEXICO"]
for strng in strngs:
matched = False
for key in dictt:
if key in strng.upper():
print key
matched = True
if not matched:
print "Null"
我希望,它可以帮助你做你想做的事。
推荐阅读
- perl - Perl,将元素附加到现有的 SOAP::Data 元素
- javascript - JQuery 表单验证什么都不做
- html - 为什么 Enter 键忽略选项卡索引?
- android - 需要帮助了解 Gradle 构建错误
- redis - 有什么方法可以在访问 Redis 后从 Redis 中逐出密钥?
- sql - 无重复的 Oracle SQL 语句
- python - 从 Pandas 数据框中访问列表中的值
- c++ - 如何将 2D 多边形三角剖分算法移植到 3D?
- jquery - 在 $(document).ready(function() 中时,console.log 不起作用
- angular - 在 Angular 6 组件 ngOnInit 函数中测试 rxjs 间隔