如何在 Pandas 数据框列中搜索特定文本?

Dom*_*m B 2 python string dataframe pandas

我想识别包含特定列文本的 Pandas csv 文件中的所有实例,在本例中为“注释”列,其中提到了“练习”一词。一旦在“Notes”列中识别出包含“excercise”关键字的行,我想创建一个名为“ExcerciseDay”的新列,如果满足“excercise”条件则为 1,否则为 0 . 我遇到了麻烦,因为文本可以在“注释”列中包含长字符串值(即“锻炼、早晨锻炼、消耗的酒精、消耗的咖啡”),我仍然希望它识别“锻炼”,即使它在更长的时间内细绳。

我尝试了下面的功能,以识别“注释”列中包含“锻炼”一词的所有文本。使用此函数时未选择任何行,我知道这可能是因为 * 运算符,但我想显示逻辑。可能有一种更有效的方法来做到这一点,但我对编程和 python 仍然比较陌生。

def IdentifyExercise(row):
    if row['Notes'] == '*exercise*':
        return 1
    elif row['Notes'] != '*exercise*':
        return 0


JoinedTables['ExerciseDay'] = JoinedTables.apply(lambda row : IdentifyExercise(row), axis=1) 
Run Code Online (Sandbox Code Playgroud)

jez*_*ael 5

转换布尔系列创建人str.containsintastype

JoinedTables['ExerciseDay'] = JoinedTables['Notes'].str.contains('exercise').astype(int)
Run Code Online (Sandbox Code Playgroud)

对于不区分大小写:

JoinedTables['ExerciseDay'] = JoinedTables['Notes'].str.contains('exercise', case=False)
                                                   .astype(int)
Run Code Online (Sandbox Code Playgroud)