【发布时间】:2021-08-26 22:15:54
【问题描述】:
我有以下字典
dictionary = {"car":1234, "light-blue":112, "orange":34, "blue":1, "cargo yellow":35}
还有下面的数据框
df_data = {"sentence": ["the summarine is a cargo yellow and orange", "the sky was an amazing light-blue, you should have seen it", "the grass is green", "why you face is purple?", "Light blue as you! HAHA", "Have you ever use the Jungle exploration?"], "extra":['a','b','c','d', 'e', 'f'] }
df = pd.DataFrame(df_data)
根据我之前提出的问题,我正在使用以下代码:
df['new_col'] = df.sentence.str.extract(pat = f"({'|'.join(dictionary.keys())})")[0]
但是我有两个问题:第一个是如果句子中有多个字典键,则无法提取它;第二个是即使不存在,它也会检索单词 car。为了解决第一个问题,我使用了以下代码:
df.sentence.str.findall(f"|".join(dictionary.keys())).apply(", ".join)
结果如下:
0 car, orange
1 light-blue
2
3
4 blue
5
但是,我仍然有汽车问题,在这种情况下还有蓝色问题。相反,我想要的是这样的:
0 cargo yellow, orange
1 light-blue
2 nan
3 nan
4 nan
5 nan
此外,您对我如何更改代码以获得此结果有任何建议:
0 cargo yellow, orange
1 light-blue
2 nan
3 nan
4 light blue
5 nan
编辑:我尝试了以下代码:
for i in dictionary.keys():
print(i,"\n",df.sentence.str.findall(rf'\b\W?{i}\W?\b'))
在这种情况下,键“汽车”没有被检索到,但考虑到我的字典有 3000 个键/值,它的效率不是很高。
谢谢!
【问题讨论】:
-
也添加几行示例数据。
-
对不起,写入的数据没有 ``` 的空格,所以被隐藏了。已添加
-
blue显然会匹配Light blue,说到car,我在结果字符串中看不到这一点。 -
使用我提供的代码?我清理内核后尝试再次运行代码,但仍然有汽车结果。
-
不知何故不在我这边,但这也是意料之中的,因为
car包含在cargo中
标签: python pandas string dictionary