首页 > 解决方案 > 如何使用 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

标签: pythonpandasnumpy

解决方案


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()

推荐阅读