首页 > 解决方案 > 如何在 python 中正确填充 4d 数组/矩阵?

问题描述

我对python很陌生,所以我非常感谢您的评论和解释。我有一个包含 40000 个条目的数据框:

id              40000 non-null int64
feature_1        40000 non-null float64
feature_2        40000 non-null float64
feature_3        40000 non-null float64
feature_4        40000 non-null float64

我需要使用系数 c_n 为每个特征计算以下方程的每个 id 编号:

eq_n=feature_1*c_1+feature_2*c_2+feature_3*c_3+feature_4*c_4

c_n可以从 0 到 1,步长为0.1(0,0.1,0.2,...1) 所以组合的数量将是11^4:11 因为步长 (0,0.1,...1) 而 4 因为4个特点。

我相信我需要先4d用系数创建数组,然后使用循环进行进一步计算。4d但我坚持使用这些系数创建和填充矩阵的过程。我尝试使用创建矩阵,np.zeros([11,4,11,4])但我不太确定我是否根据要求正确选择了维度索引,11^4而且我不太明白如何用所需的元素填充这个数组。

我从一个更简单的配置开始,创建一个零数组并在循环中更改它,但它肯定需要调整,因为它涵盖的组合数量要少得多。请看我在下面做了什么:

M=df # dataframe without Id column for simplicity 
# calc is the name of the function that makes further calculations using 
#the product of arrays 
K=[0,0,0,0] # coefficient array
J=[0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1] # steps for coefficients
ind=0 # for assigning a new element to a coefficient array
for i in K:
        for z in j:
            K[ind]=z
            calc(prod=K*M)
            print(prod)
  ind=ind+1

标签: pythonpandasnumpy

解决方案


我决定放弃使用 4d 数组的想法,我想出了一个更简单的算法:

  • 找出组合的数量并用这些组合创建一个二维数组。

    正如我之前提到的,组合的数量是 11**4

  • 因此,接下来的事情是通过使用以下函数来获取这些组合中的每一个:

    def combinations(n, m): steps = np.arange(0,1.1,0.1) qty_of_combs = n**m combs = np.zeros((qty_of_combs, m), dtype=float) for i in range(m): #for each column k = n**i q = 0 while (q < qty_of_combs): for z in range(n): for j in range(k): combs[q, i] = steps[z] q += 1 return combs

  • 最后一步是使用每个组合计算输出。

    comb_ar=combinations(11,4) for i in range(comb_ar.shape[0]): output=comb_ar[i,:]*df

这里的 df 仅包含特征列,因此我们可以计算数组的乘积。


推荐阅读