首页 > 解决方案 > python sub state names for abbrev via python dict with re.sub

问题描述

我有一个数据框,其中有一列包含州名称。这些名称混合了官方缩写和部分拼写以及完整的州名。

d = pd.DataFrame(['fla', 'fl', 'del', 'ohio', 'calif', 'ca', 'del', 'texas', 'miss', 'tx', 'new mex'],
                 columns = ["state"])

这里有一个带有状态缩写和名称的python dict:https ://code.activestate.com/recipes/577305-python-dictionary-of-us-states-and-territories/

我想查看数据框d并在 中找到最佳匹配dict并替换 中的值d['state']。我不认为我想使用replace,因为我想替换“整个单词”而不是子字符串。期望的结果:

d = ['fl', 'fl', 'de', 'oh', 'ca', 'ca', 'de', 'tx', 'ms', 'tx', 'nm']

将字典直接加载到我的控制台并调用它states_dict,我尝试了以下操作(基于此地图美国州名到字典中分别给出的两个字母首字母缩写词

d['state'] = d['state'].map(states_dict)

nan为我的数据框中的每个条目生成,d.

任何帮助将非常感激。

谢谢。

标签: pythonregexdictionarytextre

解决方案


这似乎有效:通过从每个字母中获取每个值d['state']\w*在每个字母之间添加match来搜索州名称,并以不区分大小写的方式从每个字典值的开头进行搜索。一旦找到,返回找到的小写值。

而且我认为miss一定是mo,不是mx

import pandas as pd
import re
d = pd.DataFrame(['fla', 'fl', 'del', 'ohio', 'calif', 'ca', 'del', 'texas', 'miss', 'tx', 'new mex', 'NY', 'NJ', 'NM', 'NC'], columns = ["state"])
states = {
        'AK': 'Alaska',
        'AL': 'Alabama',
        'AR': 'Arkansas',
        'AS': 'American Samoa',
        'AZ': 'Arizona',
        'CA': 'California',
        'CO': 'Colorado',
        'CT': 'Connecticut',
        'DC': 'District of Columbia',
        'DE': 'Delaware',
        'FL': 'Florida',
        'GA': 'Georgia',
        'GU': 'Guam',
        'HI': 'Hawaii',
        'IA': 'Iowa',
        'ID': 'Idaho',
        'IL': 'Illinois',
        'IN': 'Indiana',
        'KS': 'Kansas',
        'KY': 'Kentucky',
        'LA': 'Louisiana',
        'MA': 'Massachusetts',
        'MD': 'Maryland',
        'ME': 'Maine',
        'MI': 'Michigan',
        'MN': 'Minnesota',
        'MO': 'Missouri',
        'MP': 'Northern Mariana Islands',
        'MS': 'Mississippi',
        'MT': 'Montana',
        'NA': 'National',
        'NC': 'North Carolina',
        'ND': 'North Dakota',
        'NE': 'Nebraska',
        'NH': 'New Hampshire',
        'NJ': 'New Jersey',
        'NM': 'New Mexico',
        'NV': 'Nevada',
        'NY': 'New York',
        'OH': 'Ohio',
        'OK': 'Oklahoma',
        'OR': 'Oregon',
        'PA': 'Pennsylvania',
        'PR': 'Puerto Rico',
        'RI': 'Rhode Island',
        'SC': 'South Carolina',
        'SD': 'South Dakota',
        'TN': 'Tennessee',
        'TX': 'Texas',
        'UT': 'Utah',
        'VA': 'Virginia',
        'VI': 'Virgin Islands',
        'VT': 'Vermont',
        'WA': 'Washington',
        'WI': 'Wisconsin',
        'WV': 'West Virginia',
        'WY': 'Wyoming'
}

def best_match(x):
    if len(x) == 2: # Try another way for 2-letter codes
        for a,n in states.items():
            if len(n.split()) == 2:
                if "".join([c[0] for c in n.split()]).lower() == x.lower():
                    return a.lower()
    new_rx = re.compile(r"\w*".join([ch for ch in x]), re.I)
    for a,n in states.items():
        if new_rx.match(n):
            return a.lower()
        
d['state_corrected'] = d['state'].apply(lambda x: best_match(x))

结果

      state state_corrected
0       fla              fl
1        fl              fl
2       del              de
3      ohio              oh
4     calif              ca
5        ca              ca
6       del              de
7     texas              tx
8      miss              mo
9        tx              tx
10  new mex              nm
11       NY              ny
12       NJ              nj
13       NM              nm
14       NC              nc

推荐阅读