You need to enable JavaScript to run this app. Pandas报'str'对象无loc属性错误,字符串列匹配赋值如何实现?
优惠活动
大模型
产品
解决方案
定价
更多

Pandas报'str'对象无loc属性错误,字符串列匹配赋值如何实现?

报错根因

你出现AttributeError: 'str' object has no attribute 'loc'的核心问题是连续赋值逻辑错误,和loc是否支持字符串类型操作无关:

# 你的错误写法
DF = DF.loc[(DF['CustomerId'] == str(row['CustomerId'])), 'CustomerId'] = row['code']

这行是从右往左执行的连续赋值,首先会把字符串类型的row['code']赋值给DF变量,原来的DataFrame被直接覆盖成了字符串,第二次循环调用DF.loc时自然会报错字符串没有loc属性。

实现方案

方案1:修正循环逻辑

只需要去掉多余的DF = 即可,loc赋值会直接修改原DataFrame的对应位置值:

DF['CustomerId'] = DF['CustomerId'].astype(str) # 用astype比apply(str)执行效率更高
for index, row in merged.iterrows():
    match_cust_id = str(row['CustomerId'])
    # 直接用loc赋值,不需要再给DF整体赋值
    DF.loc[DF['CustomerId'] == match_cust_id, 'CustomerId'] = row['code']

方案2:更高效的向量化映射(推荐,不需要循环)

你要实现的是CustomerId到code的映射替换,用pandas内置的map方法即可完成,不需要遍历每一行,性能比iterrows循环高几十到上百倍:

# 1、先把merged转为 CustomerId:code 的映射字典,统一把CustomerId转为字符串
id_code_map = merged.set_index(merged['CustomerId'].astype(str))['code'].to_dict()
# 2、对DF的CustomerId列做映射替换,匹配到的替换为code,没匹配到的保留原值
DF['CustomerId'] = DF['CustomerId'].map(id_code_map).fillna(DF['CustomerId'])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 11:27:01