python - 如何应用依赖于当前数组元素的函数并将结果返回到当前数组元素
问题描述
数据格式:
我有一个形状为 (5,2,2) 的 3d Numpy 数组,基本上是 5 个 2x2 矩阵。
Import numpy as np
def mathFunc(arrSum):
return arrSum*2
#creating 2x2 matrices
a = np.zeros((2, 2))
b = np.ones((2, 2))
c = np.random.randint(2,3,size=(2,2))
d = np.random.randint(3,4,size=(2,2))
e = np.random.randint(4,5,size=(2,2))
#Combining 2x2 matrices to form 3D matrix
arr = np.stack((a, b, c, d, e)) # you can add more 2D arrays here if needed
print("""ORIGINAL ARRAY
---------------
{0}
---------------""".format(arr))
目标
我想检查一个 2x2 数组(以下称为 3dObject)的总和是否超过某个值,如果没有,则跳过某些计算。需要进行的计算如下:
next_3dObject = next_3dObject - function(current_3dObject, next_3dObject)
我可以使用嵌套的 for 循环来完成此操作,但这会很慢。以下是当前代码。
filt_cond = 5 #filter condition (i.e. to small of a sum)
# Using Fancy indexing and slicing
for i in range (len(arr)):
new_basis = np.random.randint(1,4,size=(2,2))
'''need to replace mathFunc() with function call that can take current_3dObject and next_3dObject
do calculation and return value to next_3dObject, this need to happen for every 3dObject after
the current_3dObject(which is where the condition was first found to be True). After 3dObjects have
been updated it will check the next 3dObject for sum condition'''
arr[i+1:][arr[i].sum() >filt_cond] *= new_basis #mathFunc(i)
print("""Array iteration {0}
---------------
{1}
---------------""".format(i,arr))
- 是否可以对这段代码进行矢量化?
- 是否可以将操作应用于 Numpy 数组的某个部分,然后将这些结果反馈回数组并再次应用操作但从不同的元素开始?
解决方案
推荐阅读
- json - 如何从 kotlin 类生成 json 模式
- excel - 所有 Outlook VBA 宏都不再工作
- node.js - 值名称带有连字符的有效负载上的 Joi 验证
- amazon-web-services - 使用 node.js 通过表单将文件上传到亚马逊 s3 存储桶
- javascript - 只发送一个刷新 JWT 请求
- android - 如何从 JSON 中获取日期
- oracle - Oracle Cloud 和 Azure 之间的 VPN
- algorithm - 将 n 个值添加到空链表以便对其进行排序的时间复杂度?
- python - 如何不在python中获得重复值
- pandas - 如何避免从 DataFrame 到 CSV 的 unicode 错误?