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

如何将pandas Series按索引匹配字典取值后相乘得到目标结果

你尝试的写法s = s.mul(s.map(dic))是完全可以实现需求的,运行后就能得到你预期的计算结果。

除此之外还有两种更简洁的实现方式可选:

  • 方法一:借助pandas的索引自动对齐特性,将字典转为Series后直接和原Series相乘:
import pandas as pd
# 你的原始数据
s = pd.Series([3,5], index=['A','B'])
dic = {'A':4, 'B':3}
# 计算
s = s * pd.Series(dic)
  • 方法二:直接映射索引对应的字典值相乘,逻辑更直白:
s = s * s.index.map(dic)

两种方法运行后输出的结果均为:

A    12
B    15
dtype: int64

小提示:如果你的Series索引存在字典中没有的键,map方法会返回NaN值,你可以通过fillna()指定默认值处理,比如要让不存在的键乘1保留原值,可以写为s = s.mul(s.map(dic).fillna(1))。

内容的提问来源于stack exchange,提问作者fred.schwartz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 08:27:03