How to use the NumPy string formatter to print a NumPy array where the output string is dependent on the array value?

Viewed 1730

I want to print a string depending on the values in a NumPy array, e.g. value 0 should lead to letter 'a'.

import numpy as np

arr = np.zeros((2,2))
arr[(0,0)] = 1
arr[(0,1)] = 2
printValues = {0:'a', 1:'b', 2:'c'}
print(np.array2string(arr, formatter={'str':lambda x: printValues[x]}))

Expected result:

[['b' 'c']
 ['a' 'a']]

Observed:

[[1. 2.]
 [0. 0.]]
2 Answers

The keyword argument formatter for array2string needs the type of the elements of the array which you want to replace, not the type which you're converting to.

So, in your example, instead of str you should use float, since 0., 1. and 2. are floats.

If you want to make sure, every element of the array is definitely printed with your formatter, use all:

import numpy as np

arr = np.zeros((2, 2))
arr[(0, 0)] = 1
arr[(0, 1)] = 2
printValues = {0: 'a', 1: 'b', 2: 'c'}
print(np.array2string(arr, formatter={'all': lambda x: printValues[int(x)]}))

See the above linked documentation for more available types. Maybe float_kind is also a good idea for you.

IIUC vectorize

np.vectorize(printValues.get)(arr)
array([['b', 'c'],
       ['a', 'a']], dtype='<U1')
Related