我正在尝试在 numpy 中构建一个矩阵。矩阵尺寸应为 (5001x7)。这是我的代码:
S=np.array([.0788,.0455,.0222,.0042,.0035,.0029,.0007])
#This is vector S, comprised of 7 scalars.
lamb=list(range(0,5001))
#This is a list of possible values for lambda, a parameter in my data.
M = np.empty([5001,7], order='C')
#This is the empty matrix which is to be filled in the iterations below.
for i in S:
for j in lamb:
np.append(M,((S[i]**2)/(lamb[j]+S[i]**2)))
我遇到的问题是 M 仍然是一个零向量矩阵。
重要细节: 1)我将最后一行指定为:
M=np.append(M,((S[i]**2)/(lamb[j]+S[i]**2)))
然后我得到一个一维数组,长度为 70,014 的值数组。我不太确定该怎么做。
2) 我已经尝试在矩阵 M 的“float”和“int”之间切换 dtype 参数。
3) 当我运行代码时收到此警告: VisibleDeprecationWarning:使用非整数而不是整数将导致将来出错 app.launch_new_instance()
4) 我正在使用 Python 3.4
我真的很感谢你的帮助。谢谢!
最佳答案
1) append
添加到数组的末尾,这就是最终数组具有 5001x7x2=70014
元素的原因。只有前半部分是零。它将数组展平为一维,因为您没有指定要附加的轴
。
2)完成整个过程的一种更“numpy”的方式是广播
S=np.array([.0788,.0455,.0222,.0042,.0035,.0029,.0007])
lamb=np.arange(0,5001)
M=(S[:,None]**2)/(lamb[None,:]+S[:,None]**2)
关于python - 构建 numpy 矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41992804/