【发布时间】:2022-01-02 09:39:42
【问题描述】:
我有这个例子 df:
df6 = pd.DataFrame({
'answer1': ['UK', 'Paris', 'Toronto'],
'answer2': ['Paris', 'Paris', 'Paris'],
'answer3': ['CA', 'CA', 'CA'],
'correct': [0.4, '3.1', 'Answer3']
})
df6:
answer1 answer2 answer3 correct
0 UK Paris CA 0.4
1 Paris Paris CA 3.1
2 Toronto Paris CA Answer3
根据 Answer1 列是 Toronto 的条件,我想将正确列中的文本“Answer3”替换为 3。
所以,我创建了一个函数,然后在 answer1 == Toronto 时使用 apply:
def replace_answer(text):
return text.replace("Answer", "")
df6.loc[df6['answer1'] == 'Toronto', 'correct'] = df6['correct'].apply(lambda x : replace_answer(x))
我收到以下错误:AttributeError: 'float' object has no attribute 'replace'
为什么我的代码处理所有正确的列,而我只选择包含多伦多作为条件的单元格?
【问题讨论】:
标签: python python-3.x pandas numpy