使用Python3和Numpy显示每个元素相对于列总数的百分比值的最佳方法是什么?

使用Python3和Numpy显示每个元素相对于列总数的百分比值的最佳方法是什么?,python,arrays,numpy,vectorization,Python,Arrays,Numpy,Vectorization,假设我有一个30000000 x 3的随机整数矩阵。我想使用Python3和Numpy显示每个元素相对于列总数的百分比值。下面是我使用的四种方法 有没有更好的方法可以推荐? 我发现方法2比方法1稍微慢一点,尽管For循环少了一个。知道为什么吗 方法3和4最好,因为它似乎使用python矢量化 我的笔记本电脑上每种方法的时间:方法1需要12000毫秒,方法2需要13500毫秒,方法3需要240毫秒,方法4需要254毫秒 # import numpy as np import time # ## m

假设我有一个30000000 x 3的随机整数矩阵。我想使用Python3和Numpy显示每个元素相对于列总数的百分比值。下面是我使用的四种方法

有没有更好的方法可以推荐? 我发现方法2比方法1稍微慢一点,尽管For循环少了一个。知道为什么吗

方法3和4最好,因为它似乎使用python矢量化

我的笔记本电脑上每种方法的时间:方法1需要12000毫秒,方法2需要13500毫秒,方法3需要240毫秒,方法4需要254毫秒

#
import numpy as np
import time
#
## make matrix of 10,000 x 3 of random integers
a = (np.random.rand(30000000).reshape(-1,3) * 10).astype(int)
nRows = a.shape[0]
nCols = a.shape[1]
print(f"nRows = {nRows}\tnCols = {nCols}\n\n")
#
## METHOD 1: with two for loops
tic = time.time()
ans = np.zeros(a.shape)
for coli in range(nCols):
    colsum = np.sum(a[:,coli])
    for rowi in range(nRows):
        ans[rowi, coli] = a[rowi, coli] / colsum
ans *= 100
print(f"{ans}")
toc = time.time()
print(f"method 1 = {1000*(toc-tic)} ms\n")
#
## METHOD 2: -- one less for loop
tic = time.time()
ans = np.zeros(a.shape)
colTotals = np.sum(a, axis=0)
for rowi in range(nRows):
    ans[rowi] = a[rowi] / colTotals
ans *= 100
print(f"\n{ans}")
toc = time.time()
print(f"method 2 = {1000*(toc-tic)} ms\n")
#
## METHOD 3: fastest way -- no for loops
tic = time.time()
ans = np.zeros(a.shape)
colTotals = np.sum(a, axis=0)
ans = a / colTotals.reshape(1, nCols)
ans *= 100
print(f"\n{ans}")
toc = time.time()
print(f"method 3 = {1000*(toc-tic)} ms\n")
#
## METHOD 4: fastest way -- no for loops
tic = time.time()
ans = np.zeros(a.shape)
colTotals = np.sum(a, axis=0).reshape(1,-1)
colTotals = np.repeat(colTotals, nRows, axis=0)
ans = a / colTotals
ans *= 100
print(f"{ans}")
toc = time.time()
print(f"method 4 = {1000*(toc-tic)} ms\n")
#

a/a.sum(axis=0)
怎么样?对不起,丹尼尔,请再看一遍这个问题。在您发表评论之后,我添加了第四种方法。