Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy - retaining the pointer when referencing a single element

I'm working with a mapping from values of a python dictionary into a numpy array like this:

import numpy as np
my_array = np.array([0, 1, 2, 3, 4, 5, 6])
my_dict = {'group_a':my_array[0:3], 'group_b':my_array[3:]}

This offers the values referenced through the dict to reflect any changes made in the full array. I need the size of the groups within the dict to be flexible. However when a group is only a single element, such as:

my_dict2 = {'group_a':my_array[0], 'group_b':my_array[1:]}

...then numpy seems to be returning the element value rather than a pointer. The value in the dict no longer reflects any changes in the array. Is there a way to clarify that I want the pointer even for a single element reference?

like image 853
user2789194 Avatar asked Sep 17 '13 20:09

user2789194


1 Answers

There is no way to do this that I know of, probably the easiest workaround is to just have the value in the dictionary be a single-element list like so:

my_dict2 = {'group_a':my_array[0:1], 'group_b':my_array[1:]}

ie,

In [2]: my_array = np.array([0, 1, 2, 3, 4, 5, 6])

In [3]: my_dict2 = {'group_a': my_array[0:1], 'group_b': my_array[1:]}

In [4]: my_dict2
Out[4]: {'group_a': array([0]), 'group_b': array([1, 2, 3, 4, 5, 6])}

In [5]: my_array[0] = 200

In [6]: my_dict2
Out[6]: {'group_a': array([200]), 'group_b': array([1, 2, 3, 4, 5, 6])}
like image 71
Cameron Sparr Avatar answered Sep 20 '22 18:09

Cameron Sparr