繁体   English   中英

根据熊猫数据框中的特定模式选择行

[英]Select rows following specific patterns in a pandas dataframe

我有一个csv文件,我已将其读入pandas数据框。 我想将两个特定的列“ Notes”和“ ActivityType”用作条件。 如果“注释”列包含“早晨锻炼”或“早晨锻炼”的字符串值和/或“活动类型”列包含任何字符串值(大多数单元格为Null,并且我不希望计算Null值),则进行新列“ MorningExercise”,如果满足两个条件,则插入1;如果不满足,则插入0。

我一直在使用下面的代码创建一个新列,并在“注释”列中满足文本条件的情况下插入1或0,但是如果“ ActivityType”列包含任何内容,我还没有弄清楚如何添加1字符串值。

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

对于“ ActivityType”列,我认为可以使用pd.notnull()函数作为标准。

我真的只需要一种方法来查看是否连续满足两个条件,如果是,则在新列中输入1或0。

您将需要使用正则表达式模式来与str.contains结合使用:

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

细节

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

模式将显示“ Morning然后进行workout exercise

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM