如何在 Python 中通过循环乘法创建多维数组?

问题描述 投票:0回答:0

我正在尝试将数组中的单个元素与 5 列的数据框相乘,以获得 ndim(5, 5, 2) 的多维数组, 然而,我使用的代码给了我

ValueError: operands could not be broadcast together with shapes (1,2) (5,5)
.

以下是我使用的数据

import numpy as np
import pandas as pd

#the array
v = np.array([6.51481987, 2.13390696])

#the df
X = {'icept': 0    1
 1    1
 2    1
 3    1
 4    1
 Name: icept, dtype: int32,
 'pvl': 0    2.533680
 1    4.255814
 2    2.269452
 3    2.930867
 4    3.555830
 Name: pvl, dtype: float64,
 'ed': 0    4.869460
 1    6.401434
 2    7.907954
 3    3.510557
 4    6.225850
 Name: ed, dtype: float64,
 'fins': 0    0.744995
 1    1.746176
 2    0.866215
 3    0.820449
 4    0.973149
 Name: fins, dtype: float64,
 'hp': 0    4.586429
 1    3.873337
 2    4.362893
 3    4.133550
 4    5.576006
 Name: hp, dtype: float64}

这是我用来创建我想做的事情的代码,这给了我错误。

v2 = [[[0 for _ in range(5)] for _ in range(5)] for _ in range(2)]
for i in enumerate(v):
    v2[:, :, i] = [i] * np.linalg.inv(X.T @ X)
python-3.x for-loop multidimensional-array matrix-multiplication multiplication
© www.soinside.com 2019 - 2024. All rights reserved.