修改ndarray中的键

时间:2014-03-18 21:32:15

标签: python numpy

我有一个看起来像这样的ndarray:

array([[ -2.1e+00,  -9.89644000e-03],
       [ -2.2e+00,   0.00000000e+00],
       [ -2.3e+00,   2.33447000e-02],
       [ -2.4e+00,   5.22411000e-02]])

将第2整数添加到第一列的最pythonic方法是什么?

array([[ -0.1e+00,  -9.89644000e-03],
       [ -0.2e+00,   0.00000000e+00],
       [ -0.3e+00,   2.33447000e-02],
       [ -0.4e+00,   5.22411000e-02]])

1 个答案:

答案 0 :(得分:3)

修改

要仅向第一列添加2,请执行

>>> import numpy as np
>>> x = np.array([[ -2.1e+00,  -9.89644000e-03],
                  [ -2.2e+00,   0.00000000e+00],
                  [ -2.3e+00,   2.33447000e-02],
                  [ -2.4e+00,   5.22411000e-02]])
>>> x[:,0] += 2 # : selects all rows, 0 selects first column
>>> x
array([[-0.1, -0.00989644],
       [-0.2,  0.        ],
       [-0.3,  0.0233447 ],
       [-0.4,  0.0522411 ]])

>>> import numpy as np
>>> x = np.array([[ -2.1e+00,  -9.89644000e-03],
                  [ -2.2e+00,   0.00000000e+00],
                  [ -2.3e+00,   2.33447000e-02],
                  [ -2.4e+00,   5.22411000e-02]])
>>> x + 2
array([[-0.1,  1.99010356],
       [-0.2,  2.        ],
       [-0.3,  2.0233447 ],
       [-0.4,  2.0522411 ]])

也许Numpy Tutorial可能对您有帮助。