Skip to main content
 首页 » 编程设计

python之按破折号 '-' 的第一次出现和最后一次出现拆分数据框文本列

2025年05月04日15EasonJim

我有一个来自 CSV 文件的数据框(“example.csv”):

row  
india - manager- intel 
india -sales-manager-amazon 
banglore -ccm- head - county- jp morgan 

我试过的代码:

df = pd.read_csv("example.csv", sep=',') 
v = df.pop('row').str.split('-', expand=True) 
v.columns = ['location', 'position', 'company'] 

预期输出:

location     position             company    
india        manager               intel   
india        sales-manager         amazon   
banglore     ccm- head - county    jp morgan 

数据:

row 
 
Burgess Hill, West Sussex, United Kingdom - ‎SVP and CIO, Global Consumer Technology - ‎American Express 
London, United Kingdom - ‎VP Technology - Workflow and Operations  and Founder - ‎Hogarth Worldwide 
Aberdeen, United Kingdom - ‎Senior Special Core Analysis Consultant/Technical Specialist - ‎COREX Group 
London, United Kingdom - ‎ED, Equity Derivatives Technology, London - ‎Morgan Stanley 
London, United Kingdom - ‎Chief Commercial Officer, Group Technology - ‎BP 
Staines, Surrey, United Kingdom - ‎Strategy & Architecture Director, Group IS - ‎Centrica 
West Sussex, United Kingdom, United Kingdom - ‎VP - Technology - ‎American Express 

请您参考如下方法:

您可以使用 split与 rsplit通过第一次出现分隔符:

df[['location','position']] = df.pop('row').str.split('-', n=1, expand=True) 
df[['position','company']] = df['position'].str.rsplit('-', n=1, expand=True) 
print (df) 
    location            position     company 
0     india              manager       intel 
1     india        sales-manager      amazon 
2  banglore   ccm- head - county   jp morgan