将元素添加到numpy数组中

时间:2017-09-25 14:58:08

标签: python arrays numpy

使用NumPy:

<!-- Modal content-->

<div class="modal fade" id="register" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Modal title here</h4>
      </div>
      <div class="modal-body">
        <form id="modal-form" class="form-horizontal" method="POST" action="bank.php">
          <div class="form-group col-md-12">
            <div class="form-group">
              <div class="col-xs-6" style="float:right;">
                <label>phone numer:</label>
                <input id="phone" type="text" class="form-control" name="phone" value="pre filled value" disabled/>
                <span id='display'></span>
              </div>
              <div class="col-xs-6" style="float:left;">
                <label>charge:</label>
                <input style="font-size:17px; font-weight:bold;" id="charge" type="text" class="form-control" name="charge" value="some other prefilled value" disabled/>
              </div>
            </div>
          </div>
          <div class="form-group">
            <div class="col-xs-12">
              <button class="btn btn-danger btn-default pull-right" data- dismiss="modal" style="margin-left:10px;">close</button>
              <button type="submit" class="btn btn-success"> submit </button>
            </div>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        modal footer
      </div>
    </div>

  </div>
</div>

如何添加列表,例如X= numpy.zeros(shape=[1, 4], dtype=np.int) ?我尝试了[1,2,3,4]numpy.add(X,[1,2,3,4]),但都没有效果!

我知道如何使用np.hstack((1,2,3,4))方法在标准Python列表中使用它,但我想使用numpy来提高性能。

1 个答案:

答案 0 :(得分:1)

Numpy数组在创建后不会改变形状。因此,在调用方法zeros((1,4), ...)之后,您已经拥有一个充满零的1x4矩阵。要将其元素设置为零以外的值,您需要使用赋值运算符:

X[0] = [1, 2, 3, 4]  # does what you are trying to achieve in your question
X[0, :] = [1, 2, 3, 4]  # equivalent to the above
X[:] = [1, 2, 3, 4]  # same
X[0, 1] = 2  # set the individual element at [0, 1] to 2