python - 如何使用 Numpy 有效地创建条件列数组?
问题描述
目标是创建一个数组,但要满足 的条件(x=>y) and (y=>z)
。
一种幼稚但有效的方法是使用嵌套for loop
,如下所示
tot_length=200
steps=0.1
start_val=0.0
list_no =np.arange(start_val, tot_length, steps)
a=np.zeros(shape=(1,3))
for x in list_no:
for y in list_no:
for z in list_no:
if (x>=y) & (y>=z):
a=np.append(a, [[x, y, z]], axis=0)
虽然没有引发内存需求问题,但执行时间明显变慢。
可以考虑的其他方法是使用下面的代码。然而,该提案只有在tot_length
低于100
. 不仅如此,这里还报告了内存问题
tot_length=200
steps=0.1
start_val=0.0
list_no =np.arange(start_val, tot_length, steps)
arr = np.meshgrid ( *[list_no for _ in range ( 3 )] )
a = np.array(list ( map ( np.ravel, arr ) )).transpose()
num_rows, num_cols = a.shape
a_list = np.arange ( num_cols ).reshape ( (-1, 3) )
for x in range ( len ( a_list ) ):
a=a[(a[:, a_list [x, 0]] >= a[:, a_list [x, 1]]) & (a[:, a_list [x, 1]] >= a[:, a_list [x, 2]])]
感谢任何可以平衡整体执行时间和内存问题的建议。我也欢迎任何使用 Pandas 的建议,如果这能让事情正常进行
要确定建议的输出是否产生了预期的输出,请使用以下参数
tot_length=3
steps=1
start_val=1
应该产生输出
1 1 1
2 1 1
2 2 1
2 2 2
解决方案
tot_length = 200
steps = 0.1
list_no = np.arange(0.0, tot_length, steps)
a = list()
for x in list_no:
for y in list_no:
if y > x:
break
for z in list_no:
if z > y:
break
a.append([x, y, z])
a = np.array(a)
# if needed, a.transpose()
推荐阅读
- php - 如何使用 pdo 删除多个表中的行
- tweets - 如何使用 tweeter api 返回有关特定位置的所有公共推文
- javascript - JQuery 无法通过 val() 函数获得正确的值
- javascript - 通过泛型参数禁用属性
- angular - Angular 6 Docker Build - Angular 编译器中的错误需要 TypeScript >=2.7.2 和 <2.8.0,但找到的是 2.8.3
- c# - 如何比较一个断言或另一个断言是否为真
- javascript - 错误解析错误:将函数部署到firebase时正则表达式标志无效
- r - 使用插入符号中的指标 ROC 优化模型
- google-bigquery - 为什么 bq 查询命令只将 100 行写入文件?
- ms-access - 从数据表复制到 ListBox