如何将这些添加到矩阵?

时间:2016-03-27 12:02:11

标签: python arrays numpy reshape

我有一个数组:

X = [[2, 2, 2],
     [3, 3, 3],
     [4, 4, 4]]

我需要在numpy数组中添加额外的列,并使用hstack和reshape填充它们。像那样:

X = [[2, 2, 2, 1],
     [3, 3, 3, 1],
     [4, 4, 4, 1]]

我的所作所为:

X = np.hstack(X, np.ones(X.reshape(X, (2,3))))

得到一个错误:

TypeError: only length-1 arrays can be converted to Python scalars

有什么问题?我做错了什么?

2 个答案:

答案 0 :(得分:4)

这里有numpy.appendnumpy.hstacknumpy.column_stack几种方式:

# numpy is imported as np
>>> x
array([[2, 2, 2],
       [3, 3, 3],
       [4, 4, 4]])
>>> np.append(x, np.ones([x.shape[0], 1], dtype=np.int32), axis=1)
array([[2, 2, 2, 1],
       [3, 3, 3, 1],
       [4, 4, 4, 1]])
>>> np.hstack([x, np.ones([x.shape[0], 1], dtype=np.int32)])
array([[2, 2, 2, 1],
       [3, 3, 3, 1],
       [4, 4, 4, 1]])
>>> np.column_stack([x, np.ones([x.shape[0], 1], dtype=np.int32)])
array([[2, 2, 2, 1],
       [3, 3, 3, 1],
       [4, 4, 4, 1]])

答案 1 :(得分:1)

您可以使用<style> .table-row{ height: 30px; position: relative; background: #fee; } .table-row-data{ margin-right: 100px; //to ensure the button does not cover the data } .table-row-data > div{ width: 25%; float: left; } .table-row-delete{ width: 100px; height: 30px; position: absolute; right: 0px; top: 0px; display: none; } .table-row:hover > .table-row-delete{ display: block; } </style> <div class="table"> <div class="table-row"> <div class="table-row-data"> <div>Some data</div> <div>Some data</div> <div>Some data</div> <div>Some data</div> </div> <div class="table-row-delete"> <button>Delete row</button> </div> </div> <div class="table-row"> <div class="table-row-data"> <div>Some data</div> <div>Some data</div> <div>Some data</div> <div>Some data</div> </div> <div class="table-row-delete"> <button>Delete row</button> </div> </div> <div class="table-row"> <div class="table-row-data"> <div>Some data</div> <div>Some data</div> <div>Some data</div> <div>Some data</div> </div> <div class="table-row-delete"> <button>Delete row</button> </div> </div> </div>

numpy.insert()

在矩阵的开头有一个:

>>> X
array([[2, 2, 2],
       [3, 3, 3],
       [4, 4, 4]])

矩阵结尾处的

>>> X=np.insert(X,0,1.0,axis=1)
>>> X
array([[1, 2, 2, 2],
       [1, 3, 3, 3],
       [1, 4, 4, 4]])