在Python中将向量堆叠成矩阵的快速方法

2024-04-25 00:25:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在python中将同一lentgh(500)的100k向量叠加到一个矩阵中,但这需要太多时间。你知道吗

这是我的密码:

stacked = all_vectors[0]
for i in range(1,100000):
    stacked = np.column_stack((stacked ,all_vectors[i]))

你知道怎么做得更快吗?你知道吗


Tags: in密码forstacknp时间rangecolumn
1条回答
网友
1楼 · 发布于 2024-04-25 00:25:24

你应该得到你想要的答案

stacked = np.column_stack(all_vectors[:100000])

看来这和

stacked = np.array(all_vectors[:100000]).transpose()

从这个交互式会话中可以看到:

>>> stacked = np.column_stack(all_vectors[:100000])
>>> sstacked = np.array(all_vectors[:100000]).transpose()
>>> stacked == sstacked
array([[ True,  True,  True, ...,  True,  True,  True],
       [ True,  True,  True, ...,  True,  True,  True],
       [ True,  True,  True, ...,  True,  True,  True],
       ...,
       [ True,  True,  True, ...,  True,  True,  True],
       [ True,  True,  True, ...,  True,  True,  True],
       [ True,  True,  True, ...,  True,  True,  True]], dtype=bool)
>>> (stacked == sstacked).all()
True

编辑:计时结果似乎更喜欢第二种方法:

%%timeit
vector = list(range(1, 1+10))
all_vectors = [vector] *100_000
result = np.column_stack(all_vectors)

396 ms ± 18.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%%timeit
vector = list(range(1, 1+10))
all_vectors = [vector] *100_000
result = np.array(all_vectors)
np.array(all_vectors[:100000]).transpose()

152 ms ± 3.16 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

相关问题 更多 >