[英]Apply Lambda Function to Multiple Columns
我希望在我的 lambda function 中包含多个列,但我遇到了不应该正确的关键问题。 我正在寻找这一行来创建一个新列,上面写着如果任务中存在“决定”,然后将其标记为决定。 否则,如果“项目”中存在“里程碑”,则将其标记为里程碑。 否则,将其保留为当前任务类型。
today['New_Type'] = today[['Task','Projects','Type'].apply(lambda x,y,z: "Decision" if "Decision" in x else "Milestone" if "Milestone" in y else z)
任何想法如何调整这个?
如果您使用名为 function 的常规名称,这将更容易调试。 请务必在调用apply
时指定axis
参数。 您编写的 function 需要采用一个参数,该参数是三列值的元组,因此最好立即解压缩它们以提高可读性:
import pandas as pd
def task_type(row):
task, project, old_type = row
if 'decision' in task.lower():
return 'Decision'
if 'milestone' in project.lower():
return 'Milestone'
return old_type
today = pd.DataFrame({'Task': ['Make a decision.',
'Do something else.',
'Write a function.'],
'Projects': ['alpha', 'Milestone 7',
'gamma'],
'Type': ['old 1', 'old 2', 'old 3']})
today['New_Type'] = today.apply(task_type, axis=1)
today
Task Projects Type New_Type
0 Make a decision. alpha old 1 Decision
1 Do something else. Milestone 7 old 2 Milestone
2 Write a function. gamma old 3 old 3
避免Series.apply
(隐藏循环)并考虑使用numpy.where
或numpy.select
的向量化条件逻辑方法:
today['New_Type'] = np.where(
today['Task'].str.contains('Decision', regex = False),
'Decision',
np.where(
today['Task'].str.contains('Milestone', regex = False),
'Milestone',
today['Task']
)
)
today['New_Type'] = np.select(
condlist = [
today['Task'].str.contains('Decision', regex = False),
today['Task'].str.contains('Milestone', regex = False)
],
choicelist = ['Decision', 'Milestone'],
default = today['Task']
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.