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

Pandas中匹配子串后用前一列值替换当前列值时出现KeyError的问题求助

Pandas中匹配子串后用前一列值替换当前列值时出现KeyError的问题求助

我现在用的是Python 3.6.8,手里有一个包含name和sport两列的DataFrame df,想要把sport列中包含子串"replace this value for"的单元格替换成对应行name列的值。

我的DataFrame是用这段代码生成的:

import pandas as pd
df = pd.DataFrame({'name': ['Bob', 'Jane', 'Alice'],
                   'sport': ['tennis', 'replace this value for Jane', 'replace this value for Alice']})

于是我写了下面这段代码:

row_num=df.index[df.iloc[:,1].str.contains('replace this value for')]
for num in row_num:
  df.loc[num,1]=df.loc[num,0]

但运行后出现了这样的错误:

# If we have a listlike key, _check_indexing_error will raise

KeyError: 0

能不能请大家帮我解决这个错误呀?

备注:内容来源于stack exchange,提问作者Tanvi Mirza

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 18:28:06