通过带有 re.sub 的 python dict 得到缩写的 python 子状态名称

jva*_*nti 3 python regex text dictionary python-re

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

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

这里有一个带有状态缩写和名称的Python字典: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']
Run Code Online (Sandbox Code Playgroud)

将字典直接加载到我的控制台中并调用它states_dict,我尝试了以下操作(根据此地图将美国州名映射到字典中单独给出的两个字母缩写词

d['state'] = d['state'].map(states_dict)
Run Code Online (Sandbox Code Playgroud)

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

任何帮助将非常感激。

谢谢。

Rys*_*ech 5

这似乎有效:通过从每个字母中获取每个值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))
Run Code Online (Sandbox Code Playgroud)

结果

      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
Run Code Online (Sandbox Code Playgroud)

  • 是的,你不能真正寻找部分匹配。没有办法将密歇根州与密歇根州、密苏里州、明尼苏达州或密西西比州分开。我认为你必须寻找常见缩写的精确匹配并拒绝其余的。甚至“Miss”也可以是普通的密西西比河或密苏里州的开始。即使是人类也做不到。 (2认同)