我有一个单词和一个Pandas数据框,其中有一列字符串值现在我试图找到数据帧中的行,这些行的字符串部分包含该单词。
我读过ExtractAll()方法,但我不知道如何使用它,也不知道它是否是正确的答案。

最佳答案

使用此测试数据(从Chris Albon中修改和借用):

raw_data = {'regiment': ['Nighthawks Goons', 'Nighthawks Goons', 'Nighthawks', 'Nighthawks', 'Dragoons', 'Dragoons', 'Dragoons', 'Dragoons', 'Scouts', 'Scouts', 'Scouts', 'Scouts'],
        'company': ['1st', '1st', '2nd', '2nd', '1st', '1st', '2nd', '2nd','1st', '1st', '2nd', '2nd'],
        'name': ['Miller', 'Jacobson', 'Ali', 'Milner', 'Cooze', 'Jacon', 'Ryaner', 'Sone', 'Sloan', 'Piger', 'Riani', 'Ali'],
        'preTestScore': [4, 24, 31, 2, 3, 4, 24, 31, 2, 3, 2, 3],
        'postTestScore': [25, 94, 57, 62, 70, 25, 94, 57, 62, 70, 62, 70]}
df = pd.DataFrame(raw_data, columns = ['regiment', 'company', 'name', 'preTestScore', 'postTestScore'])

您可以使用此命令查找仅包含单词goons的行(忽略大小写):
df[df['regiment'].str.contains(r"\bgoons\b", case = False)]

10-04 14:13