0

I have a structured numpy array which I'm trying to modify in-place, but the new values are not reflected.

import numpy as np

dt = {'names':['A', 'B', 'C'],
        'formats': [np.int64, np.int64, np.dtype('U8')]}
arr = np.empty(0, dtype=dt)

arr = np.append(arr, np.array([(1, 100, 'ab')], dtype = dt))
arr = np.append(arr, np.array([(2, 800, 'ax')], dtype = dt))
arr = np.append(arr, np.array([(3, 700, 'asb')], dtype = dt))
arr = np.append(arr, np.array([(4, 600, 'gdf')], dtype = dt))
arr = np.append(arr, np.array([(5, 500, 'hfg')], dtype = dt))

print(arr)

arr[arr['A'] == 1]['B'] = 555

print(arr)

Is it even possible to change values in structured array? What could be the workaround?

Please don't suggest Pandas or other library based solution since I'm only allowed to use numpy at work.

1
  • 1
    As explenation you're creating a copy which you then modify. Commented Oct 12, 2022 at 13:07

1 Answer 1

5

You can reverse the indexing you're doing: first select the field you're interested in, which returns a view on the original array (as described in the documentation), as a normal numpy array, that you can modify:

import numpy as np

dt = {'names':['A', 'B', 'C'],
        'formats': [np.int64, np.int64, np.dtype('U8')]}
arr = np.empty(0, dtype=dt)

arr = np.append(arr, np.array([(1, 100, 'ab')], dtype = dt))
arr = np.append(arr, np.array([(2, 800, 'ax')], dtype = dt))
arr = np.append(arr, np.array([(3, 700, 'asb')], dtype = dt))
arr = np.append(arr, np.array([(4, 600, 'gdf')], dtype = dt))
arr = np.append(arr, np.array([(5, 500, 'hfg')], dtype = dt))

print(arr)

arr['B'][arr['A'] == 1] = 555

print(arr)
Sign up to request clarification or add additional context in comments.

Comments

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.