如何在 NumPy 中将一个轴扩展为两个轴?

How can I expand one axis to 2 axes in NumPy?

假设我有一个任意维度的字符串 ndarray。例如:[["abc", "def"], ["ghi", "jkl"]]。现在,我想将每个字符串拆分为单独的字符,以便基本上添加第二维中的轴:[[['a', 'd'], ['b', 'e'], ['c', 'f']], [['g', 'j'], ['h', 'k'], ['i', 'l']]]。或者更好地说,它应该表现得像 MATLAB 将字符串数组转换为字符数组:

A = 
  2×2 string array
    "abc"    "def"
    "ghi"    "jkl"

应该变成:

  2×3×2 char array
ans(:,:,1) =
    'abc'
    'ghi'
ans(:,:,2) =
    'def'
    'jkl'

我尝试了 np.frompyfuncnp.apply_over_axisnp.apply_from_axis 等功能,但到目前为止对我没有任何效果。有什么妙招吗?

反过来其实很简单:

def row_to_string(row):
    return ''.join([chr(int(x)) for x in row])

return np.apply_along_axis(row_to_string, 1, np.asarray(x))

编辑:有关 3D 示例,请参阅此要点:https://gist.github.com/PeterTillema/215f0a6474849a06001e10804e5a6eca

In [159]: alist = [["abc", "def"], ["ghi", "jkl"]]
In [160]: np.frompyfunc(list,1,1)(alist)
Out[160]: 
array([[list(['a', 'b', 'c']), list(['d', 'e', 'f'])],
       [list(['g', 'h', 'i']), list(['j', 'k', 'l'])]], dtype=object)
In [161]: np.array(np.frompyfunc(list,1,1)(alist).tolist())
Out[161]: 
array([[['a', 'b', 'c'],
        ['d', 'e', 'f']],

       [['g', 'h', 'i'],
        ['j', 'k', 'l']]], dtype='<U1')

从那里您可以转换为所需的布局。

将字符串拆分为字符是一项 python 任务。 Numpy 没有特殊的字符串代码,只有 np.char 将字符串方法应用于字符串 dtype 数组元素的函数。

frompyfunc 是将 python 函数应用于数组元素的便捷工具。它不编译任何东西,但通常在速度上与列表理解相当,而且可能更方便。