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
相关产品推荐
相关产品推荐

