在pandas数据框中选择遵循特定模式的行

Dom*_*m B 2 python regex string dataframe pandas

我有一个csv文件,我读入了pandas数据帧.有两个特定的列,'Notes'和'ActivityType',我想用作标准.如果'Notes'列包含字符串值'Morning exercise'或'Morning exercise'和/或'ActivityType'列包含任何字符串值(大多数单元格为空,我不想计算Null值),那么make一个新列'MorningExercise'并在满足任一条件时插入1,如果不满足则插入0.

我一直在使用下面的代码创建一个新列,如果在'Notes'列中满足文本条件,则插入1或0,但如果'ActivityType'列包含任何内容,我还没想出如何包含1字符串值.

JoinedTables['MorningExercise'] = JoinedTables['Notes'].str.contains(('Morning workout' or 'Morning exercise'), case=False, na=False).astype(int)
Run Code Online (Sandbox Code Playgroud)

对于'ActivityType'列,我认为使用该pd.notnull()函数作为批评.

我真的只需要在python中查看是否连续满足任一条件,如果是,则在新列中输入1或0.

cs9*_*s95 5

你需要设计一个正则表达式模式来使用str.contains:

regex = r'Morning\s*(?:workout|exercise)'
JoinedTables['MorningExercise'] = \
       JoinedTables['Notes'].str.contains(regex, case=False, na=False).astype(int)
Run Code Online (Sandbox Code Playgroud)

细节

Morning       # match "Morning"
\s*           # 0 or more whitespace chars
(?:           # open non-capturing group
workout       # match "workout" 
|             # OR operator
exercise      # match "exercise"
)
Run Code Online (Sandbox Code Playgroud)

该模式将寻找Morning后跟workout exercise.