翻译数组

问题描述 投票:0回答:1

在 python 中,我有一个这样的数组:

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

我知道第一个位置是“a”,第二个是“b”,依此类推

如何将“ones”转换为“as”、“bs”、……?

还没有。一点线索都没有。

python-3.x numpy-ndarray
1个回答
0
投票

我相信你可能想使用数组索引:

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

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

输出:

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

用 a/b/c 替换连续的 1……

from string import ascii_lowercase

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

输出:

array([[' ', ' ', 'a'],
       ['b', ' ', 'c'],
       [' ', 'd', 'e'],
       [' ', ' ', ' ']], dtype='<U1')
© www.soinside.com 2019 - 2024. All rights reserved.