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

如何在Pandas DataFrame中将整数的每位数字映射为对应字符串

解决方案

首先注意你的字典中存在重复键'8',Python字典会保留最后一次赋值的结果,所以实际'8'对应的是'I',这和你期望的输出一致。

下面是简洁且符合Python/Pandas风格的实现方式:

import pandas as pd

# 修正后的字典(保留重复键的最后一个值)
dictionary = {
    '1':'A',
    '2':'B',
    '3':'C',
    '4':'D',
    '5':'E',
    '6':'F',
    '7':'G',
    '8':'I',
    '9':'J',
    '0':'L'
}

ds = {'col1' : [12345,67890], 'col2' : [12364,78910]}
df = pd.DataFrame(data=ds)

# 创建字符转换表,然后对col1进行转换
trans_table = str.maketrans(dictionary)
df['col1_transformed'] = df['col1'].astype(str).str.translate(trans_table)

print(df)

代码说明:

  1. str.maketrans(dictionary):将映射字典转换为字符串转换表,这是Python内置的高效字符转换工具。
  2. df['col1'].astype(str):把col1的整数类型转为字符串类型,方便逐字符处理。
  3. str.translate(trans_table):对每个字符串执行批量字符替换,这是Pandas的矢量化操作,比apply循环更高效,也更符合Pandas的最佳实践。

运行后输出结果:

col1   col2 col1_transformed
0  12345  12364            ABCDE
1  67890  78910            FGHIJ

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 07:05:20