【问题标题】:Select rows following specific patterns in a pandas dataframe在熊猫数据框中选择遵循特定模式的行
【发布时间】:2018-03-13 00:39:22
【问题描述】:

我有一个 csv 文件,我读入了 pandas 数据框。我想将两个特定列“Notes”和“ActivityType”用作标准。如果 'Notes' 列包含字符串值 'Morning exercise' 或 'Morning exercise' 和/或 'ActivityType' 列包含任何字符串值(大多数单元格是 Null 并且我不希望 Null 值计算在内)然后新列 '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)

对于“ActivityType”列,我会考虑使用pd.notnull() 函数作为标准。

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

【问题讨论】:

  • 您正在创建一个 True/False 布尔值,使用它! (提示它永远不会为空)

标签: python regex string pandas dataframe


【解决方案1】:

您需要设计一个正则表达式模式以与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

【讨论】:

    猜你喜欢
    • 2018-05-20
    • 2022-01-21
    • 1970-01-01
    • 2021-07-17
    • 1970-01-01
    • 2015-12-03
    • 2015-03-29
    • 2021-02-09
    • 2020-12-23
    相关资源
    最近更新 更多