Skip to main content
 首页 » 编程设计

python之根据其他列值重命名列

2024年09月07日8kevingrace

我有一个包含以下列的数据框:

Region | LA code | LA Name 
----------------------------------------- 
London |    201  | City of London 
London |    202  | Camden 
London |    203  | Greenwich 
London |    204  | Hackney 
London |    205  | Hammersmith and Fulham 
London |    206  | Islington 
London |    207  | Kensington and Chelsea 
London |    208  | Lambeth 
London |    209  | Lewisham 
London |    210  | Southwark 
London |    211  | Tower Hamlets 
London |    212  | Wandsworth 
London |    213  | Westminster 
London |    301  | Barking and Dagenham 
London |    302  | Barnet 
London |    303  | Bexley 
London |    304  | Brent 
London |    305  | Bromley 
London |    306  | Croydon 
London |    307  | Ealing 
London |    308  | Enfield 
London |    309  | Haringey 
London |    310  | Harrow 
London |    311  | Havering 
London |    312  | Hillingdon 
London |    313  | Hounslow 
London |    314  | Kingston upon Thames 
London |    315  | Merton 
London |    316  | Newham 
London |    317  | Redbridge 
London |    318  | Richmond upon Thames 
London |    319  | Sutton 
London |    320  | Waltham Forest 

我的问题是,在 LA 代码在 201 - 213 范围内的情况下,将伦敦重命名为内伦敦,在 LA 代码在 301 - 320 范围内的情况下,将伦敦重命名为外伦敦,有什么简单快捷的方法?

谢谢。

请您参考如下方法:

这两个问题都由 pd.Series.between 回答。

m = df['LA Code'].between(201, 213) 
df.loc[m, 'Region'] = 'Inner ' + df.loc[m, 'Region'] 
# df.loc[m, 'Region'] = df.loc[m, 'Region'].radd('Inner ') 

还有,

m = df['LA Code'].between(301, 320) 
df.loc[m, 'Region'] = 'Outer ' + df.loc[m, 'Region']