沿轴线连接numpy字符串数组?

时间:2015-09-18 18:00:08

标签: python string numpy

我有一个2-d numpy字符串数组。有没有办法连接每一行中的字符串,然后用分隔符字符串连接结果字符串,例如换行?

示例:

pic = np.array([ 'H','e','l','l','o','W','o','r','l','d']).reshape(2,5)

我想得到:

"Hello\nWorld\n"

3 个答案:

答案 0 :(得分:7)

在numpy的并不难:

>>> import numpy as np
>>> pic = np.array([ 'H','e','l','l','o','W','o','r','l','d']).reshape(2,5)
>>> pic
array([['H', 'e', 'l', 'l', 'o'],
       ['W', 'o', 'r', 'l', 'd']], 
      dtype='|S1')
>>> '\n'.join([''.join(row) for row in pic])
'Hello\nWorld'

还有np.core.defchararray模块,它具有处理字符数组的“好东西” - 但是,它声明这些只是python内置函数和标准库函数的包装器,所以你可能不会得到任何通过使用它们获得真正的加速。

答案 1 :(得分:7)

你有正确的想法。这是一个vectorized NumPythonic实施尝试继续这些想法 -

# Create a separator string of the same rows as input array
separator_str = np.repeat(['\n'], pic.shape[0])[:,None]

# Concatenate these two and convert to string for final output
out = np.concatenate((pic,separator_str),axis=1).tostring()

np.column_stack -

的单行班次
np.column_stack((pic,np.repeat(['\n'], pic.shape[0])[:,None])).tostring()

示例运行 -

In [123]: pic
Out[123]: 
array([['H', 'e', 'l', 'l', 'o'],
       ['W', 'o', 'r', 'l', 'd']], 
      dtype='|S1')

In [124]: np.column_stack((pic,np.repeat(['\n'], pic.shape[0])[:,None])).tostring()
Out[124]: 'Hello\nWorld\n'

答案 2 :(得分:2)

一种方法是使用str.join()和列表理解,例如 -

In [1]: import numpy as np

In [2]: pic = np.array([ 'H','e','l','l','o','W','o','r','l','d']).reshape(2,5)

In [3]: pic
Out[3]:
array([['H', 'e', 'l', 'l', 'o'],
       ['W', 'o', 'r', 'l', 'd']],
      dtype='<U1')

In [4]: '\n'.join([''.join(x) for x in pic])
Out[4]: 'Hello\nWorld'

如果你真的需要最后的\n,你可以在加入字符串后连接它。示例 -

In [5]: '\n'.join([''.join(x) for x in pic]) + '\n'
Out[5]: 'Hello\nWorld\n'