【发布时间】:2018-11-22 10:00:53
【问题描述】:
我正在尝试使用 if-else 逻辑编写一个函数,该函数将修改我的数据框中的两列。但它不起作用。以下是我的功能
def get_comment_status(df):
if df['address'] == 'NY':
df['comment'] = 'call tomorrow'
df['selection_status'] = 'interview scheduled'
return df['comment']
return df['selection_status']
else:
df['comment'] = 'Dont call'
df['selection_status'] = 'application rejected'
return df['comment']
return df['selection_status']
然后执行函数为:
df[['comment', 'selection_status']] = df.apply(get_comment_status, axis = 1)
但我遇到了错误。我究竟做错了什么 ?我的猜测可能是 df.apply() 语法错误
错误信息:
TypeError: 'str' 对象不能被解释为整数 KeyError:('address', '发生在索引 0')
示例数据框:
df = pd.DataFrame({'address': ['NY', 'CA', 'NJ', 'NY', 'WS', 'OR', 'OR'],
'name1': ['john', 'mayer', 'dylan', 'bob', 'mary', 'jake', 'rob'],
'name2': ['mayer', 'dylan', 'mayer', 'bob', 'bob', 'tim', 'ben'],
'comment': ['n/a', 'n/a', 'n/a', 'n/a', 'n/a', 'n/a', 'n/a'],
'score': [90, 8, 88, 72, 34, 95, 50],
'selection_status': ['inprogress', 'inprogress', 'inprogress', 'inprogress', 'inprogress', 'inprogress', 'inprogress']})
我也想过使用 lambda 函数,但它不起作用,因为我试图使用 '=' 为 'comment' 和 'selection_status' 列赋值
注意:我检查了this question,它与标题相似,但不能解决我的问题。
【问题讨论】:
-
如果你也列出错误很有用
-
查看你的返回语句:只有每个分支中的第一个被执行。您需要返回其他内容,基本上是同时返回两个值。
-
你能发布你想要的输出吗?
-
请注意,
.apply不适用于数据框,而是用于一行。对于您的代码,这无关紧要,但是在函数中命名变量df意味着您对 apply 的思考不正确,这将在以后引起混淆。 -
@9769953 - 这是非常有用的注释。谢谢。
标签: python python-3.x pandas if-statement