[英]Checking ending characters in dataframe and replacing them
我想根據以下條件在我的 Pandas 數據框中添加兩個新列
像這樣的東西:
Text
bla bla bla ...
once upon a time
pretty little liars
Batman ...
預期的
Text T Clean
bla bla bla ... 1 bla bla bla
once upon a time 0 once upon a time
pretty little liars 0 pretty little liars
Batman ... 1 Batman
我嘗試應用正則表達式,但 str.endwith 可能是檢查句子是否以 ... 結尾的更好方法,因為分配了一個布爾值(我的 T 列)。
我試過如下: df['Text'].str.endswith('...')
但我需要用 1 和 0 創建一個新列。為了清理文本,我會檢查T
是否為真:如果是的,我會在最后刪除...
df['Clean'] = df['Text'].str.rstrip('...')
或df['Clean'] = df['Text'].str[:-3]
(但它不包括任何邏輯條件或有關...
信息)
或df['Clean'] = df['Text'].str.replace(r'...$', '')
重要的是我考慮以...
結尾的句子,以避免刪除...
在句子中間具有不同含義。
對於第一列,我將使用您建議的方法:
df['T'] = df['Text'].str.endswith('...')
(從技術上講,這將創建一個布爾列,而不是整數列。如果您關心這一點,可以使用astype()
進行轉換。)
對於第二列,我將無條件替換:
df['Clean'] = df['Text'].str.replace(r'...$', '')
如果它不是以 ... 結尾,它就不會做任何事情。
如果您只想用該屬性替換那些文本行上的“結尾”省略號:
df.loc[df['Text'].str.endswith('...') == True, 'ends_in_ellipsis'] = 1
df.loc[df['ends_in_ellipsis'] == 1, 'Text_2'] = df.loc[df['ends_in_ellipsis'] == 1, 'Text'].str.rstrip('...')
現在,如果您想在一行中完成所有操作(雖然對其他人來說可讀性較差,但您保存了一個虛擬列及其占用的內存):
df.loc[df['Text'].str.endswith('...') == True, 'Text_2'] = df.loc[df['Text'].str.endswith('...') == True, 'Text'].str.rstrip('...')
讓我們試試endswith
+ rstrip
df['new1']=df.Text.str.endswith('...').astype(int)
df['new2']=df.Text.str.rstrip(' ...') # notice rstrip will not remove any ... in the mid
df
Text new1 new2
0 bla bla bla ... 1 bla bla bla
1 once upon a time 0 once upon a time
2 pretty little liars 0 pretty little liars
3 Batman ... 1 Batman
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.