首页 > 解决方案 > 如何从与我的字典中的“值”匹配的文本字段中提取字符串并将字典的键返回到输出中的新列中?

问题描述

我想从描述字段(我的 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

标签: pythonstringpandasdictionarydataframe

解决方案


如果我理解你的话,你想要这样的东西:

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"

我希望,它可以帮助你做你想做的事。


推荐阅读