max n*n重塑2d numpy数组函数,该函数丢弃最小值并返回列平均值之和?

2024-06-06 04:09:29 发布

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

我正在为我的数据科学课研究这个问题: 编写一个接受整数的函数,并执行以下操作: 创建一个从0到输入整数的数字数组 将其重塑为最大的n*n数组,丢弃任何多余的元素(例如,如果要生成10 x 10,但有102个元素,则丢弃最后2个) 返回列平均值的累计和

到目前为止,我有下面的代码用于矩阵整形,但是对于大的数字,它会超时。如能就如何完成这一问题的第一步提出任何建议,我们将不胜感激。在

    import numpy as np
def ranged_arr(n):
    ranged_arr = np.arange(0,n+1,1)
    if len(ranged_arr)%int(len(ranged_arr)**0.5)== 0:
        array = ranged_arr.reshape(int(len(ranged_arr)**0.5),int(len(ranged_arr)**0.5))
        return array
    else:
        len(ranged_arr)%int(len(ranged_arr)**0.5)!= 0
        idx = 0
        new_arr = np.arange(0,n-idx,1)
        while len(new_arr)%int(len(new_arr)**0.5)!= 0:
            idx +=1
        q = new_arr.reshape(int(len(new_arr)**0.5),int(len(new_arr)**0.5))
        return q

Tags: 元素newlenreturnnp数字整数数组
2条回答

从@Alber8295开始的代码来看,剩下的问题是:

def ranged_arr(n):
    #Creates an array of the numbers from 0 up to that inputted integer 
    ranged_arr = np.arange(0,n+1)

    #Reshapes it to be the largest n * n array that it could be

    #Find the largest dim
    largest_dim = math.floor(math.sqrt(n+1))
    #Find the size of the array that will be reshaped
    last_index = largest_dim**2
    #Take the slice of the original array that could be reshaped
    fitted_ranged_arr = ranged_arr[:last_index]
    #Finally, reshape it!
    reshaped_range_arr = fitted_ranged_arr.reshape((largest_dim,largest_dim))

    # get the sum of the col means 

    #get the means of each col
    col_means = np.mean(reshaped_range_arr,axis=0)
    # get the sum of the means 
    sum_of_means = col_means.sum()
    #Return everything, so you can check the steps
    return ranged_arr,largest_dim,fitted_ranged_arr,reshaped_range_arr,col_means, sum_of_means

    print(sum_of_means)

让我们保持甜蜜和简单:)

首先,让我们分解你的问题,你必须:

1。创建一个从0到输入整数的数组

2。将其重塑为最大的m x m阵列,使其成为

2.1。找到最大尺寸(m)

现在让我们编写那个Python函数!在

def ranged_arr(n):
    #Creates an array of the numbers from 0 up to that inputted integer 
    ranged_arr = np.arange(0,n+1)

    #Reshapes it to be the largest n * n array that it could be

    #Find the largest dim
    largest_dim = math.floor(math.sqrt(n+1))
    #Find the size of the array that will be reshaped
    last_index = largest_dim**2
    #Take the slice of the original array that could be reshaped
    fitted_ranged_arr = ranged_arr[:last_index]
    #Finally, reshape it!
    reshaped_range_arr = fitted_ranged_arr.reshape((largest_dim,largest_dim))

    #Return everything, so you can check the steps
    return ranged_arr,largest_dim,fitted_ranged_arr,reshaped_range_arr

我把它上传到我的Github,这样你就可以用一些测试来检查它here

相关问题 更多 >