gpt4 book ai didi

python - 在python中向矩阵添加列

转载 作者:太空狗 更新时间:2023-10-29 22:06:36 24 4
gpt4 key购买 nike

在 python 中是否有一些方法可以将列添加到矩阵中。我想在 python 中的 mxn 矩阵的开头添加一列。例如,我有 1000x100 矩阵,我想把它变成 1000x101 矩阵。我想在开头插入包含所有 ones 的新列,即这将是我新的第一列。在 python 中可以吗?

这是我的代码-vector1是一个列表,cnt是1000

data=np.array(vector1)  
shape = ( cnt, 100 )
data=data.reshape(shape)

现在我想在开始时添加一个新列

最佳答案

您在 numpy.hstacknumpy.ones 中查找的函数:

例如,

import numpy as np

X = np.random.uniform(size=(10,3))
n,m = X.shape # for generality
X0 = np.ones((n,1))
Xnew = np.hstack((X,X0))

print(X)
[[ 0.78614426 0.24150772 0.94330932]
[ 0.60088812 0.20427371 0.19453546]
[ 0.31853252 0.31669057 0.82782995]
[ 0.71749368 0.54609844 0.74924888]
[ 0.86883981 0.54634575 0.83232409]
[ 0.89313181 0.8006561 0.05072146]
[ 0.79492088 0.07750024 0.45762175]
[ 0.92350837 0.20587178 0.76987197]
[ 0.0092076 0.0044617 0.04673518]
[ 0.69569363 0.3315923 0.15093861]]

print(X0)
[[ 1.]
[ 1.]
[ 1.]
[ 1.]
[ 1.]
[ 1.]
[ 1.]
[ 1.]
[ 1.]
[ 1.]]

print(Xnew)
[[ 0.78614426 0.24150772 0.94330932 1. ]
[ 0.60088812 0.20427371 0.19453546 1. ]
[ 0.31853252 0.31669057 0.82782995 1. ]
[ 0.71749368 0.54609844 0.74924888 1. ]
[ 0.86883981 0.54634575 0.83232409 1. ]
[ 0.89313181 0.8006561 0.05072146 1. ]
[ 0.79492088 0.07750024 0.45762175 1. ]
[ 0.92350837 0.20587178 0.76987197 1. ]
[ 0.0092076 0.0044617 0.04673518 1. ]
[ 0.69569363 0.3315923 0.15093861 1. ]]

关于python - 在python中向矩阵添加列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32827269/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com