1

I have a numpy structured array that looks like this:

>>> arr
array([('2020-03-26T21:30',    0, 0.),
    ('2020-03-26T21:31',    1, 0.),
    ('2020-03-26T21:32',    2, 0.), ...,
    ('2020-03-27T22:27', 1497, 0.),
    ('2020-03-27T22:28', 1498, 0.),
    ('2020-03-27T22:29', 1499, 0.)],
    dtype=[('time', '<M8[m]'), ('idx', '<i4'), ('value', '<f4')])

I want to select a certain row and set its value as some value. How can I do this?

I tried this:

>>> arr[ np.where(arr['time'] == np.datetime64('now', 'm')) ]['value'] = 10

But it seems it just extracts the row and makes a new array out of the original array. How can I actually set a value and keep it in the original array?

1
  • Try putting the field indexing first Commented Mar 27, 2020 at 15:02

1 Answer 1

1

In general, if you want to assign values to an existing array, you need to assign the value to a view of the original, rather than a copy. When you use array indexing this way, you'll always get a copy, as you've realized.

In the case of record arrays, you can get a view by accessing the field first:

>>> arr['value'][numpy.where(arr['time'] == b'2020-03-26T21:31')] = 100
>>> arr
array([(b'2020-03-26T21:30',    0,   0.),
       (b'2020-03-26T21:31',    1, 100.),
       (b'2020-03-26T21:32',    2,   0.),
       (b'2020-03-27T22:27', 1497,   0.),
       (b'2020-03-27T22:28', 1498,   0.),
       (b'2020-03-27T22:29', 1499,   0.)],
      dtype=[('time', 'S20'), ('idx', '<i4'), ('value', '<f4')])
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.