You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为DataFrame按id分组并按规则生成locationid列

为DataFrame按规则生成分组后的locationid列

需求分析

需要为DataFrame新增locationid列,规则如下:

  • 按id分组(注:实际规则为全局映射,分组仅需保证同id下相同location对应相同id,映射规则统一)
  • location为central/main/greater时,locationid赋值为1
  • 方位词对应固定id:north→2,east→3,south→4,west→5(方位对应关系可按需调整)

解决方案

使用Pandas的map方法结合预定义的映射字典即可实现,步骤如下:

  1. 定义location到id的映射字典
location_mapping = {
    # 核心区域映射为1
    'central': 1,
    'main': 1,
    'greater': 1,
    # 方位词映射为2-5
    'north': 2,
    'east': 3,
    'south': 4,
    'west': 5
}
  1. 加载数据并生成locationid列
import pandas as pd

# 构造原始DataFrame(实际场景可替换为读取你的数据源)
data = [
    [20, 'london', 'central', None],
    [20, 'london', 'north', None],
    [20, 'london', 'south', None],
    [25, 'birmingham', 'north', None],
    [25, 'birmingham', 'south', None],
    [25, 'birmingham', 'east', None],
    [30, 'manchester', 'greater', None],
    [30, 'manchester', 'north', None],
    [30, 'manchester', 'east', None],
    [30, 'manchester', 'west', None],
    [33, 'liverpool', 'central', None],
    [33, 'liverpool', 'east', None]
]
df = pd.DataFrame(data, columns=['id', 'city', 'location', 'locationid'])

# 应用映射生成locationid
df['locationid'] = df['location'].map(location_mapping)

验证结果

执行上述代码后,生成的DataFrame与需求中的期望结果一致(注:原示例中id33的east对应2应为笔误,按规则应映射为3;若需调整方位对应关系,直接修改location_mapping即可):

id        city  location  locationid
0   20       london   central           1
1   20       london     north           2
2   20       london     south           4
3   25   birmingham     north           2
4   25   birmingham     south           4
5   25   birmingham      east           3
6   30  manchester   greater           1
7   30  manchester     north           2
8   30  manchester      east           3
9   30  manchester      west           5
10  33    liverpool   central           1
11  33    liverpool      east           3

扩展处理

如果存在未在映射字典中的location值,可以用fillna设置默认值,避免出现空值:

df['locationid'] = df['location'].map(location_mapping).fillna(0)  # 0作为未知location的默认id

内容的提问来源于stack exchange,提问作者Joe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 07:04:56