python - How to iterate an arbitrary function using vectorisation
问题描述
I would like to iterate a given function in a pandas dataframe without using a for loop, i.e using vectorisation.
I have already written a for loop for this function but I would like to improve the efficiency of this output.
def f(x,y,operation):
if operation=='add':
return x+y
elif operation=='power':
return x**y
else:
print('type can only be power or add')
df = pd.DataFrame({
'first_entry':[1,np.nan,np.nan,np.nan,np.nan],
'operation':[np.nan,'plus','power','plus','plus'],
'operand':[np.nan,3,2,4,1]
})
first_entry operation operand expected_result
1 NA NA 1
NA plus 3 4 (= 1+3)
NA power 2 16 (=4**2)
NA plus 4 20 (=16+4)
NA plus 1 21 (=20+1)
I want to return
pd.Series(1,4,16,20,21)
, i.e. iterate f
over the dataframe
Alternative question: Suppose now
def g(x,y,operation):
if operation=='relative':
return x*(1+y)
elif operation=='absolute':
return x+y
else:
print('type can only be relative or absolute')
Can I write a function with list comprehension to give the expected result?
first_entry operation operand expected_result
1 NA NA 1
NA relative 3 4 (= 1*(3+1)
NA absolute 2 6 (=4+2)
NA relative 4 30 (=6*(4+1)
NA absolute 1 31 (=30+1)
解决方案
推荐阅读
- autodesk-forge - 在 Autodesk A360 中删除项目、文件夹和项目
- powershell - 在远程机器上运行 powershell 脚本
- roku - 如何在 BrightScript 中检查网络连接
- javascript - 在另一个调用使用 php (Laravel) 执行长时间作业时制作 ajax
- python - 如何清理 csv 文件的输出?
- java - 如何修复第一次单击“设置”为空,第二次单击仅获取日期
- oracle - oracle如何获取内部过程的输出
- excel - 关闭 Access 创建的 Excel 实例后留下的 Excel 进程
- regex - 如何根据行中前一个单元格的值计算不同长度的行中的单元格?
- performance - Qt 在 10 毫秒内画出 100 万个圆圈