Python max n*n重塑2d numpy数组函数,该函数丢弃最小值并返回列平均值之和?
我正在为我的数据科学课程研究这个问题: 编写一个接受整数的函数,并执行以下操作: 创建从0到输入整数的数字数组 将其重塑为最大的n*n数组,丢弃任何多余的元素(即,如果要制作10 x 10,但有102个元素,则丢弃最后2个) 返回列平均值的累积和 到目前为止,我有下面的代码用于矩阵重塑,但是对于大的数字它会超时。任何关于如何完成此问题第一步的建议都将不胜感激Python max n*n重塑2d numpy数组函数,该函数丢弃最小值并返回列平均值之和?,python,numpy,matrix,memory-management,Python,Numpy,Matrix,Memory Management,我正在为我的数据科学课程研究这个问题: 编写一个接受整数的函数,并执行以下操作: 创建从0到输入整数的数字数组 将其重塑为最大的n*n数组,丢弃任何多余的元素(即,如果要制作10 x 10,但有102个元素,则丢弃最后2个) 返回列平均值的累积和 到目前为止,我有下面的代码用于矩阵重塑,但是对于大的数字它会超时。任何关于如何完成此问题第一步的建议都将不胜感激 import numpy as np def ranged_arr(n): ranged_arr = np.arange(
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
让我们保持甜蜜和简单:) 首先,让我们分解您的问题,您必须: 一,。创建一个从0到输入整数的数字数组 二,。将其重塑为最大的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,这样你就可以通过@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)
非常感谢,这真的简化了问题!很高兴看到你完美地解决了剩下的练习^^