Eri*_*ikR 8 python string numpy
我有一个2-d numpy字符串数组.有没有办法连接每一行中的字符串,然后用分隔符字符串连接结果字符串,例如换行符?
例:
pic = np.array([ 'H','e','l','l','o','W','o','r','l','d']).reshape(2,5)
Run Code Online (Sandbox Code Playgroud)
我想得到:
"Hello\nWorld\n"
Run Code Online (Sandbox Code Playgroud)
在 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'
Run Code Online (Sandbox Code Playgroud)
还有一个np.core.defchararray模块具有处理字符数组的"好东西" - 但是,它声明这些仅仅是python内置函数和标准库函数的包装器,所以你可能无法通过使用它们获得任何真正的加速.
那里你有正确的想法.这是一个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()
Run Code Online (Sandbox Code Playgroud)
或者单行np.column_stack-
np.column_stack((pic,np.repeat(['\n'], pic.shape[0])[:,None])).tostring()
Run Code Online (Sandbox Code Playgroud)
样品运行 -
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'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8593 次 |
| 最近记录: |