簡體   English   中英

Python DataFrame:刪除/替換列中所有值的部分字符串

[英]Python DataFrame: Remove/Replace part of a string for all values in a column

在 Dataframe“df”中,我有一個名為“公司”的列。 在那里我有一個以“-CP”結尾的公司列表,問題是空格並不總是在同一個地方,並且在一些條目中缺少破折號“-”。 我想從所有條目中刪除“-CP”。

輸入

公司
小蘋果 - CP
蘋果-CP
測試Apple-CP
小蘋果 - CP
趣味蘋果CP
霍華德 P 三角洲 - CP

Output

公司
蘋果腸
蘋果腸
蘋果腸
蘋果腸
蘋果腸
霍華德 P 三角洲

這是我的代碼,但是當我運行它時沒有任何變化

df['Company'] = df['Company'].str.replace("-CP'","") 
df['Company'] = df['Company'].str.replace("- CP'","") 
df['Company'] = df['Company'].str.replace(" - CP'","") 
df['Company']=df['Company'].str.replace("-CP","")
df['Company'] = df['Company'].str.replace("- CP","") 
df['Company'] = df['Company'].str.replace(" - CP","") 

您可以將str.replace與正則表達式一起使用,以包括破折號可能缺失的情況 ( -? ) 以及CP字符串之間的所有空格變體。

company = df.Company.str.replace('\s*-?\s*CP\s*$','', regex=True)

公司Output

Out[5]:
0      Intest Apple
1      Intest Apple
2      Intest Apple
3      Intest Apple
4      Intest Apple
5    Howard P Delta
Name: Company, dtype: object

暫無
暫無

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

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