python - 如何为 pandas df 正确编写 if-then lambda 语句?
问题描述
我有以下代码:
data = [[11001218, 'Value', 93483.37, 'G', '', 93483.37, '', '56117J100', 'FRA', 'Equity'],
[11001218, 'Value', 3572.73, 'G', 3572.73, '', '56117J100', '', 'LUM', 'Equity'],
[11001218, 'Value', 89910.64, 'G', 89910.64, '', '56117J100', '', 'WAR', 'Equity'],
[11005597, 'Value', 72640313.34,'L','',72640313.34, 'REVR21964', '','IN2', 'Repo']
]
df = pd.DataFrame(data, columns = ['ID', 'Type', 'Diff', 'Group', 'Amount','Amount2', 'Id2', 'Id3', 'Executor', 'Name'])
def logic_builder(row, row2, row3):
if row['Name'] == 'Repo' and row['Group'] == 'L':
return 'Fine resultant'
elif (row['ID'] == row2['ID']) and (row['ID'] == row3['ID']) and (row['Group'] == row2['Group']) and (row['Group'] == row3['Group']) and (row['Executor'] != row2['Executor']) and (row['Executor'] != row3['Executor']):
return 'Difference in Executor'
df['Results'] = df.apply(lambda row: logic_builder(row, row2, row3), axis=1)
如果您查看前 3 行,它们在技术上都是相同的。它们包含相同的 ID、类型、组和名称。唯一的区别是执行者,因此我希望我的 if-then 语句返回“执行者的差异”。我无法弄清楚如何纠正 if-then 以查看我上面提到的字段的所有具有相似属性的行。
谢谢你。
解决方案
您可以传递单行,然后确定其索引并使用 查找其他行df.iloc[index]
。
这里有一个例子
def logic_builder(row):
global df #you need to access the df
i = row.name #row index
#get next rows
try:
row2 = df.iloc[i+1]
row3 = df.iloc[i+2]
except IndexError:
return
if row['Name'] == 'Repo' and row['Group'] == 'L':
return 'Fine resultant'
elif (row['ID'] == row2['ID']) and (row['ID'] == row3['ID']) and (row['Group'] == row2['Group']) and (row['Group'] == row3['Group']) and (row['Executor'] != row2['Executor']) and (row['Executor'] != row3['Executor']):
return 'Difference in Executor'
df['Results'] = df.apply(logic_builder, axis=1)
当然,由于结果取决于接下来的两行,因此您不能在数据帧的最后两行上运行它。
推荐阅读
- python - 为什么要给估值或加息?
- c - 如何使用 datetime('now', '-1 day') 使用准备好的语句检索 sqlite3 数据库中的行?
- reactjs - 错误提示:- 空闲,状态从启动变为启动,使用 SIGTERM 停止所有进程,进程以状态 143 退出
- azure-data-factory - 如何在 Azure 数据工厂 - Web 活动中使用 PATCH 请求?
- java - 单例对象的间谍在 Junit 中调用真实方法,并且在为 Mocked 对象一起运行所有测试时方法模拟不起作用
- python - 如何使用 PYTHONBREAKPOINT 启动 ipython?
- linux - 使用入口点时环境变量导出不起作用?
- python - 带有 open 和 pd.to_csv 的 Python
- html - 下拉菜单位于内容页面后面或向下滚动时
- r - 无效的下标类型“列表”