Home > OS >  Structured numpy array not modified in place
Structured numpy array not modified in place

Time:10-12

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.

CodePudding user response:

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)
  • Related