Modify keys in ndarray

Question:

I have a ndarray that looks like this:

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]])

Whats the most pythonic way to add the integer 2 to the first column to give:

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]])
Asked By: ipburbank

||

Answers:

Edit:

To add 2 to the first column only, do

>>> 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 ]])

Perhaps the Numpy Tutorial may help you.

Answered By: wflynny
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.