有没有办法使用 FuzzyWuzzy
或类似库在数据框列中搜索值?
我试图在考虑模糊匹配的同时在一列中找到与另一列中的值相对应的值。所以
因此,例如,如果我在一列中有州名,在另一列中有州代码,我如何找到佛罗里达州的州代码,即餐饮时的 FL像“Flor”这样的缩写?
换句话说,我想找到与“Flor”对应的州名称的匹配项,并获得相应的州代码“FL”。
非常感谢任何帮助。
最佳答案
如果缩写都是前缀,您可以对状态的短版本或长版本使用.startswith()
字符串方法。
>>> test_value = "Flor"
>>> test_value.upper().startswith("FL")
True
>>> "Florida".lower().startswith(test_value.lower())
True
但是,如果您有更复杂的缩写,difflib.get_close_matches
可能会做你想做的事!
>>> import pandas as pd
>>> import difflib
>>> df = pd.DataFrame({"states": ("Florida", "Texas"), "st": ("FL", "TX")})
>>> df
states st
0 Florida FL
1 Texas TX
>>> difflib.get_close_matches("Flor", df["states"].to_list())
['Florida']
>>> difflib.get_close_matches("x", df["states"].to_list(), cutoff=0.2)
['Texas']
>>> df["st"][df.index[df["states"]=="Texas"]].iloc[0]
'TX'
您可能想尝试/排除 IndexError
从 difflib 读取返回列表的第一个成员,并可能调整截止值以减少与关闭状态的错误匹配(可能将所有状态提供为可能性 某些用户或需要更多的关闭状态字母)。
您可能还会看到结合这两者的最佳结果;在尝试模糊匹配之前先测试前缀。
综合考虑
def state_from_partial(test_text, df, col_fullnames, col_shortnames):
if len(test_text) < 2:
raise ValueError("must have at least 2 characters")
# if there's exactly two characters, try to directly match short name
if len(test_text) == 2 and test_text.upper() in df[col_shortnames]:
return test_text.upper()
states = df[col_fullnames].to_list()
match = None
# this will definitely fail at least for states starting with M or New
#for state in states:
# if state.lower().startswith(test_text.lower())
# match = state
# break # leave loop and prepare to find the prefix
if not match:
try: # see if there's a fuzzy match
match = difflib.get_close_matches(test_text, states)[0] # cutoff=0.6
except IndexError:
pass # consider matching against a list of problematic states with different cutoff
if match:
return df[col_shortnames][df.index[df[col_fullnames]==match]].iloc[0]
raise ValueError("couldn't find a state matching partial: {}".format(test_text))
当心以“New”或“M”(可能还有其他)开头的状态,它们都非常接近并且可能需要特殊处理。测试会在这里创造奇迹。
关于python - 模糊搜索 Pandas 中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64142393/