簡體   English   中英

Python / Pandas從結尾刪除特定的字符串

[英]Python/Pandas remove specific string from ending

我試圖從pandas數據幀中的列中刪除結尾的'OF'。 我嘗試'rstrip','拆分',但它也刪除'O'和'F',我只需要刪除'OF'。 怎么做? 我不知道為什么當我專門通過'OF'時,rstrip會刪除'O'和'F'。 對不起,如果以前問過這個問題,我還是找不到一個。 謝謝。

樣本數據:

l1 = [1,2,3,4]
l2 = ['UNIVERSITY OF CONN. OF','ONTARIO','UNIV. OF TORONTO','ALASKA DEPT.OF']
df = pd.DataFrame({'some_id':l1,'org':l2})
df

some_id org
1       UNIVERSITY OF CONN. OF
2       ONTARIO
3       UNIV. OF TORONTO
4       ALASKA DEPT.OF

嘗試:

df.org.str.rstrip('OF')
# df.org.str.split('OF')[0] # Not what I am looking for

結果:

0    UNIVERSITY OF CONN. # works
1                  ONTARI # 'O' was removed
2         UNIV. OF TORONT # 'O' was removed
3            ALASKA DEPT. # works

需要最終輸出:

0    UNIVERSITY OF CONN. 
1                  ONTARIO
2         UNIV. OF TORONTO
3            ALASKA DEPT.

你可以嘗試這個正則表達式:

df.org = df.org.str.replace('(OF)$','')

其中$表示字符串的結尾。 要么

df.org.str.rstrip('(OF)')

似乎按預期工作。

輸出:

0    UNIVERSITY OF CONN. 
1                 ONTARIO
2        UNIV. OF TORONTO
3            ALASKA DEPT.
Name: org, dtype: object

str.extract

捕獲所有內容,直到並且不包括單詞末尾的單個可選'OF' 我為測試用例添加了幾行。

df['extract'] = df.org.str.extract('(.*?)(?=(?:OF$)|$)')

#   some_id                     org               extract
#0        1  UNIVERSITY OF CONN. OF  UNIVERSITY OF CONN. 
#1        2                 ONTARIO               ONTARIO
#2        3        UNIV. OF TORONTO      UNIV. OF TORONTO
#3        4          ALASKA DEPT.OF          ALASKA DEPT.
#4        5            fooOFfooOFOF            fooOFfooOF
#5        6                      fF                    fF
#6        7                   Seven                 Seven

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM