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

Python Pandas中np.where映射城市列失败,求解决方案

类别列转整数列的实现方案

你要把City列的类别值(A/B/C)转换成整数(1/2/3)用于热力图,原代码存在两个问题:

  • 条件判断误用赋值符号=,应该用比较符号==
  • 最内层的np.where未设置默认返回值分支

修正后的np.where写法

import numpy as np
import pandas as pd

# 假设df为你的目标DataFrame
df['city_new'] = np.where(df['City'] == 'A', 1,
                   np.where(df['City'] == 'B', 2,
                   np.where(df['City'] == 'C', 3, 0))) # 末尾添加默认值,比如0

更简洁的实现方式

方法1:字典映射(map)

可读性强,适合类别数量少的场景:

city_mapping = {'A':1, 'B':2, 'C':3}
df['city_new'] = df['City'].map(city_mapping)

方法2:pandas factorize函数

适合类别较多的场景,自动为每个唯一类别分配整数ID(默认从0开始,可+1调整为从1开始):

df['city_new'] = df['City'].factorize()[0] + 1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 09:15:41