【发布时间】:2021-12-29 15:43:47
【问题描述】:
目前我正在努力寻找一种优雅的方式来解决我面临的问题。
我有一个大数据框,其中包含一个带有部门名称的列:
输入
demo = pd.DataFrame(
{'Department':
['AA','AA1','BB team 1','AA but also a bit of nonsense',
'BB','AA','department BB','Complete nonsense']}
)
Department
AA
AA1
BB team 1
AA but also a bit of nonsense
BB
AA
department BB
Complete nonsense
我还有一个已知部门的列表:
known_departments = ['AA','BB']
可以看出,列表中有三类部门:
- 与已知部门完全匹配的部门,应保持不变。
- 作为已知部门变体的部门。 即:它包含部门名称,但存在一些其他文本。这些应该映射到原始已知部门。
- 完整的废话部门,与已知部门没有任何匹配,这些也应该保持不变。
期望的输出
Department Department_simplified
AA AA
AA1 AA
BB team 1 BB
AA but also a bit of nonsense AA
BB BB
AA AA
department BB BB
Complete nonsense Complete nonsense
更新
感谢 Chris 和 sophocles 的回答。虽然使用 str.extract 和 str.findall 看起来更优雅,但在性能方面,apply+function 在我的实际 df 上都优于:
Solution %%timeit -n20
Chris 1.65s ± 311 ms per loop (mean ± std. dev. of 7 runs, 20 loops each)
sophocles 1.14s ± 294 ms per loop (mean ± std. dev. of 7 runs, 20 loops each)
Paul 680 ms ± 174 ms per loop (mean ± std. dev. of 7 runs, 20 loops each)
【问题讨论】:
-
这能让你开始吗?也有一些矢量化的解决方案stackoverflow.com/questions/48590488/…
-
我去看看,谢谢。
-
@CallumDA。这可行,但与我在下面的答案相同。我想我对矢量化解决方案更感兴趣。
-
什么是统计数据?部门多久与部门简化相同?有多少部门?平均部门名称是多长,平均部门名称是多长时间?
标签: python pandas performance