我有一个 csv 文件,我将其读入 pandas 数据帧。我想将两个特定列用作条件:“Notes”和“ActivityType”。如果“注释”列包含“晨练”或“晨练”字符串值和/或“ActivityType”列包含任何字符串值(大多数单元格为空,我不希望计算空值),则进行一个新列“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()
函数作为标准。
我真的只需要 python 中的一种方法来查看连续是否满足任一条件,如果满足,则在新列中输入 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
。
关于python - 在 pandas 数据框中选择遵循特定模式的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46517089/