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

标签 python pandas dataframe

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

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

我的问题是,将伦敦重命名为内伦敦(其中洛杉矶代码在 201 - 213 范围内),将伦敦重命名为外伦敦(其中洛杉矶代码在 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']

关于python - 根据其他列值重命名列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50614323/

相关文章:

python - split() 中的字符串列表无法转换为 int()

python - 两个具有一个可选参数差异的 url 映射到 Flask Restful 中的相同资源

android - 在 Android 上使用 Python 检索 WiFi 数据

python - 给定一些数据,我如何预测 matplotlib 将在何处绘制刻度?

python - 使用 pandas 创建多索引

python - 展平多索引 pandas 数据框中的一对一映射

python - 使用 Pandas 将多行转换为单行

python - Pandas 数据帧 : Is there a difference in performance in replacing values by column and row?

python - 从今天的日期中减去 pandas Dataframe 的值

python - Dataframe 的重复数据删除返回空对象