【发布时间】:2026-02-02 15:50:01
【问题描述】:
我有一个数据集,我尝试只选择与列表中定义的字符串完全匹配的行。
list = ['P:34.', 'R:ES.']
df = pd.DataFrame({
'Date':['2021-01-01', '2021-01-01', '2021-01-01', '2021-01-02', '2021-01-02', '2021-01-02', '2021-01-02', '2021-01-03'],
'Code':['P:34. R:ES.', 'R:ESB.', 'K2P:P:341.', 'R:ESZ', 'P:34.', 'R.ES7.', 'P 34 5', 'P:32. R:ES.'],
'Ratings':[9.0, 8.0, 5.0, 3.0, 2, 3, 6, 5]})
我使用函数str.contains 相应地选择行,但是这样我得到的行与字符串不完全匹配。
sample = df[df.Code.str.contains('|'.join(list),na=False)]
我尝试只获取列表中包含完全字符串的行(也考虑字符串末尾的点),这将是这样的:
df_exact_match = pd.DataFrame({
'Date':['2021-01-01', '2021-01-02', '2021-01-03'],
'Code':['P:34. R:ES.', 'P:34.', 'P:32. R:ES.'],
'Ratings':[9.0, 2, 5]})
非常感谢您的建议:)
【问题讨论】: