【问题标题】:How to effeciently create conditional columns arrays using Numpy?如何使用 Numpy 高效地创建条件列数组?
【发布时间】:2020-10-21 14:02:40
【问题描述】:

目标是创建一个数组,但要满足(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)

虽然没有引发内存需求问题,但执行时间明显变慢。

可以考虑的其他方法是使用下面的代码code。然而,该提案只有在tot_length 小于100 时才能完美运行。不仅如此,据报道here

会出现内存问题
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,您正在为a 分配大约30GB 的内存,这并不小。

标签: python pandas numpy


【解决方案1】:
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()

【讨论】:

  • 我看不出这与 OP 的解决方案有何不同。
  • 这样可以避免调用np.append,这比使用列表并在最后转换为数组要慢
【解决方案2】:

这样的东西有用吗?

tot_length=200
steps=0.1
list_no = np.arange(0.0, tot_length, steps)
x, y, z = np.meshgrid(*[list_no for _ in range(3)], sparse=True)
a = ((x>=y) & (y>=z)).nonzero()

这仍将使用 8GB 内存用于中间布尔值数组,但避免重复调用很慢的 np.append

【讨论】:

  • 嗨,Eric,我刚刚注意到,a 中的所有值都是四舍五入的。这是预期的吗?是因为 nonzero() 返回非浮点类型吗?例如,如果我设置 tot_length=0.3 , steps=0.1, start_val=0.1 ,您提出的解决方案将返回一个整数值而不是十进制值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-24
  • 1970-01-01
  • 2020-07-24
  • 2016-07-14
  • 1970-01-01
  • 1970-01-01
  • 2021-11-21
相关资源
最近更新 更多