3 回答

TA貢獻1829條經(jīng)驗 獲得超4個贊
meshgrid您可以在使用with后對“列”重新排序[:,[0,2,1,3]],如果由于列數(shù)較多而需要使列表動態(tài)化,那么您可以看到我答案的結(jié)尾:
np.array(np.meshgrid(theta_array, XY_array)).T.reshape(-1,4)[:,[0,2,1,3]]
輸出:
array([[ 1. , 1. , 44.0394952 , 505.81099922]],
[[ 1. , 1. , 61.03882938, 515.97253226]],
[[ 1. , 1. , 26.69851841, 525.18083012]],
...,
[[ 14. , 14. , 73.86032436, 973.91032818]],
[[ 14. , 14. , 103.96923524, 984.24366761]],
[[ 14. , 14. , 93.20663129, 995.44618851]])
如果您有很多列,您可以動態(tài)創(chuàng)建此列表:[0,2,1,3]使用列表理解。例如:
n = new_arr.shape[1]*2
lst = [x for x in range(n) if x % 2 == 0]
[lst.append(z) for z in [y for y in range(n) if y % 2 == 1]]
lst
[0, 2, 4, 6, 1, 3, 5, 7]
然后,您可以重寫為:
np.array(np.meshgrid(theta_array, XY_array)).T.reshape(-1,4)[:,lst]

TA貢獻1779條經(jīng)驗 獲得超6個贊
您可以使用itertools.product:
out = np.array([*product(theta_array, XY_array)])
out = out.reshape(out.shape[0],-1)
輸出:
array([[ 1. , 10. , 44.0394952 , 505.81099922],
[ 1. , 10. , 61.03882938, 515.97253226],
[ 1. , 10. , 26.69851841, 525.18083012],
...,
[ 4. , 14. , 73.86032436, 973.91032818],
[ 4. , 14. , 103.96923524, 984.24366761],
[ 4. , 14. , 93.20663129, 995.44618851]])
也就是說,這看起來非常像XY 問題。你想用這個數(shù)組做什么?

TA貢獻1865條經(jīng)驗 獲得超7個贊
正如此處的側(cè)面/補充參考一樣,我們對兩種解決方案的執(zhí)行時間進行了比較。完成此特定操作itertools所需的時間比同等操作多 10 倍numpy。
%%time
for i in range(1000):
z = np.array(np.meshgrid(theta_array, XY_array)).T.reshape(-1,4)[:,[0,2,1,3]]
CPU times: user 299 ms, sys: 0 ns, total: 299 ms
Wall time: 328 ms
%%time
for i in range(1000):
z = np.array([*product(theta_array, XY_array)])
z = z.reshape(z.shape[0],-1)
CPU times: user 2.79 s, sys: 474 μs, total: 2.79 s
Wall time: 2.84 s
添加回答
舉報