【发布时间】:2020-06-26 20:13:46
【问题描述】:
我有一个数据框,它有 2 列。称它为国家/地区,ID
我想获取对应于所选国家值的 ID 值。
但是我想通过字符串变量动态选择 Country 的值,只要字符串变量的某些部分存在于 Country 列中
为了。例如,
s = 'subang - sultan abdu'
我希望它能够在 Country (Malaysia) 中查找 Last row,因为它在那里有部分匹配的“subang”,然后获取相应的 ID。
我试过了:
df.ID[df.Country.str.contains(s, flags =re.IGNORECASE,na= False)].values[0]
因为 Series.contains 默认使用正则表达式搜索来匹配。
但是它没有在这里出现并给出错误。
IndexError: index 0 is out of bounds for axis 0 with size 0
如果我的字符串有效
s = 'kuala lumpur'
df.ID[df.Country.str.contains(s, flags =re.IGNORECASE,na= False)].values[0]
13
任何帮助为什么它给出错误并且没有按照包含的预期进行部分匹配?
【问题讨论】:
-
可以试试
difflib:df.loc[df['Country'].eq(difflib.get_close_matches("subang - sultan abdu",df['Country'],n=1)[0]),'ID'] -
这是熊猫方法吗?
-
没有
import difflib然后试试 -
不想导入另一个库。想检查一下这是否可以在没有它的情况下完成
-
好的,如果您确定字符串将被拆分,下面的答案会建议正确的方法