簡體   English   中英

如何在 python 的 2D 陣列中加速 2D arrays?

[英]How to speed up 2D arrays in 2D array in python?

我正在研究如何加快我的一項功能。 function是用多個相同大小的二維arrays調用的。 我想將它們組合成最后兩個維度為 3x3 的 4D,然后得到整個數組的特征值。

我已經設法使用兩個嵌套for循環來做到這一點,但是它比我想要的要慢一些,那么有什么好方法可以加快代碼速度嗎?

def principal(xx, xy, xz, yy, yz, zz):

    import numpy as np

    xx = np.array(xx)
    xy = np.array(xy)
    xz = np.array(xz)
    yy = np.array(yy)
    yz = np.array(yz)
    zz = np.array(zz)

    size = np.shape(xx)
    Princ = np.empty((size[1], size[0], 3, 3))
    for j in range(size[1]):
        for i in range(size[0]):
            Princ[j, i, :, :] = np.array([[xx[i, j], xy[i, j], xz[i, j]],
                                          [xy[i, j], yy[i, j], yz[i, j]],
                                          [xz[i, j], yz[i, j], zz[i, j]]])
    Princ = np.linalg.eigvalsh(Princ)

    return Princ


import numpy as np

number_arrays_1 = 3
number_arrays_2 = 4

xx = np.ones((number_arrays_1, number_arrays_2))*80
xy = np.ones((number_arrays_1, number_arrays_2))*30
xz = np.ones((number_arrays_1, number_arrays_2))*0
yy = np.ones((number_arrays_1, number_arrays_2))*40
yz = np.ones((number_arrays_1, number_arrays_2))*0
zz = np.ones((number_arrays_1, number_arrays_2))*60

Princ = principal(xx, xy, xz, yy, yz, zz)
print(Princ)

The reason I convert with xx = np.array(xx) is that in the larger program, I pass a pandas dataframe rather than a numpy array into the function.

這看起來像一個簡單的堆棧和重塑操作:

def principal(xx, xy, xz, yy, yz, zz):
    princ = np.stack((xx.T, xy.T, xz.T, xy.T, yy.T, yz.T, xz.T, yz.T, zz.T), axis=-1).reshape(*xx.shape[::-1], 3, 3)
    return = np.linalg.eigvalsh(princ)

如果輸入已經是 arrays,則不需要在輸入上顯式調用np.array 數據幀上的xx.values()應返回 numpy 值。

另一種方法是構建數組,然后將 3x3 維度換到后面。 這可能會降低效率,因為第一種方法使 3x3 維度連續,而這種方法沒有:

princ = np.array([[xx, xy, xz], [xy, yy, yz], [xz, yz, zz]]).T

不是很相關,但您可以像這樣更快地生成 arrays:

target_shape = (3, 4)
values = np.array([80, 30, 0, 40, 0, 60])
xx, xy, xz, yy, yz, zz = np.full((6, *target_shape), values.reshape(-1, 1, 1))

事實上,如果您的數據允許,您甚至可以節省拆包時間:

data = np.full((6, *target_shape), values.reshape(-1, 1, 1))
principal(*data)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM