简体   繁体   English

从numpy数组获取元素并创建新的numpy数组的最快方法

[英]Fastest way to get elements from a numpy array and create a new numpy array

I have numpy array called data of dimensions 150x4 I want to create a new numpy array called mean of dimensions 3x4 by choosing random elements from data . 我有一个名为150x4 datanumpy数组,我想通过从data选择随机元素来创建一个新的名为3x4meannumpy数组。

My current implementation is: 我当前的实现是:

    cols = (data.shape[1])
    K=3
    mean = np.zeros((K,cols))
    for row in range(K):
        index = np.random.randint(data.shape[0])
        for col in range(cols):
            mean[row][col] = data[index][col]

Is there a faster way to do the same? 有没有更快的方法可以做到这一点?

You can specify the number of random integers in numpy.randint (third argument). 您可以在numpy.randint (第三个参数)中指定随机整数的数量。 Also, you should be familiar with numpy.array 's index notations. 另外,您应该熟悉numpy.array的索引符号。 Here, you can access all the elements in one row by : specifier. 在这里,您可以通过: specifier访问一行中的所有元素。

mean = data[np.random.randint(0,len(data),3),:]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM