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

创建DataFrame新列时遇“cannot reindex on an axis with duplicate labels”错误求助

解决pandas的ValueError: cannot reindex on an axis with duplicate labels问题

错误原因

ref.loc[df['currency']]返回的结果索引是df['currency']的取值(包含重复的'EUR'),而原df的索引是0-4的连续整数。当你尝试将两者相乘时,pandas会尝试按索引对齐,但重复的索引标签导致对齐失败,触发该错误。

解决方案

方法1:使用map映射取值

直接通过currency列映射ref中对应的forex值,生成与原df索引一致的Series后再相乘:

df['salary_eur'] = df['salary'] * df['currency'].map(ref['forex'])

方法2:使用merge合并数据

先将两个DataFrame按currency合并,再计算转换后的薪资:

# 合并ref中的forex列到df
df = df.merge(ref[['forex']], left_on='currency', right_index=True)
# 计算转换后薪资
df['salary_eur'] = df['salary'] * df['forex']
# 可选:删除临时的forex列
df.drop('forex', axis=1, inplace=True)

结果验证

执行上述任一方法后,df的salary_eur列会正确生成:

salarycurrencysalary_eur
10EUR10.0
11EUR11.0
12USD126.0
13SEK26.0
14JPY74.2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 17:07:12