簡體   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