0

I'm working on a script that converts ids of school names to actual school names structured in a numpy array.

For example

[[1,2,3],[3,6,7]]

becomes

[[school-a,school-b,school-c],[school-c,school-f,school-g]

The school and ids sit together in a python dictionary.

I've tried doing this:

for x in np.nditer(finalarray, op_flags=['readwrite']):
    x[...] = school_ids.get(int(x))
    print(school_ids.get(int(x)))
print(finalarray)

but that gave the error:

ValueError: invalid literal for int() with base 10: 'school-a'

it's important that the structure of the numpy array stays the same, because I also thought of just iterating every item, but then the structure is lost.

DJosh
  • 15
  • 1
  • 5
  • Are you sure you want to be using a numpy array for this? Why don't you just use python lists? – roganjosh Jan 04 '19 at 17:35
  • The array is generated via numpy – DJosh Jan 04 '19 at 17:36
  • `finalarray` is a `dtype` integer array. The `x[...]=...` step tries to convert the string (from the dictionary) to an integer so it can put it in `finalarray`. You want a new string dtype array, not a rewrite of the original. `nditer` is not a good tool for beginners. It's too complicated, and doesn't offer any speed advantages. – hpaulj Jan 04 '19 at 17:44

2 Answers2

1

Using the solution from this post:

x = np.array([[1,1,3], [2,2,2]])
d = {1: 'a', 2:'b', 3:'c'}
np.vectorize(d.get)(x)
>> array([['a', 'a', 'c'],
   ['b', 'b', 'b']], dtype=object)
Tarifazo
  • 4,118
  • 1
  • 9
  • 22
  • It is mentioned both in the question title and the post itself that the ids map to the school IDs from a dictionary. It's quite possible that the alignment with indices is purely coincidental; this isn't what the OP asked for – roganjosh Jan 04 '19 at 17:41
0

suppose I have a dict :

dictt = {
    0: 'school-a',
    1: 'school-b',
    2: 'school-c',
    3: 'school-d',
    4: 'school-e',
    5: 'school-f',
    6: 'school-g',
    7: 'school-h',
    8: 'school-i'
}

_ids = np.array([[1,2,3],[3,6,7]])
school_ids = np.array(list(dictt.values()))
print school_ids[_ids-1]

got:

[['school-a' 'school-b' 'school-c']
 ['school-c' 'school-f' 'school-g']]
itonia.x.i
  • 27
  • 5