Search code examples
python-3.xnumpy-ndarray

Translate nd array


In python I have a nd array like this:

0 0 1
1 0 1
0 1 1
0 0 0

I know that the first position is “a”, second is “b”, and so on.

How can I transform “ones” to “as”, “bs”, … ?

Nothing yet. Not a clue.


Solution

  • I believe you might want to use array indexing:

    a = np.array([[0,0,1],
                  [1,0,1],
                  [0,1,1],
                  [0,0,0]])
    
    out = np.array(['a', 'b'])[a]
    

    Output:

    array([['a', 'a', 'b'],
           ['b', 'a', 'b'],
           ['a', 'b', 'b'],
           ['a', 'a', 'a']], dtype='<U1')
    

    replacing sequential 1s by a/b/c…

    from string import ascii_lowercase
    
    out = np.r_[[' '], list(ascii_lowercase)
                ][np.where(a.ravel(), a.cumsum(), 0).reshape(a.shape)]
    

    Output:

    array([[' ', ' ', 'a'],
           ['b', ' ', 'c'],
           [' ', 'd', 'e'],
           [' ', ' ', ' ']], dtype='<U1')