方法#1
那些partition 函数似乎并未针对所有事件进行分区。为了解决我们的情况,我们可以使用np.char.split 来获取拆分字符串,然后使用masking,array-assignment,就像这样 -
def partitions(a, sep):
# Split based on sep
s = np.char.split(a,sep)
# Get concatenated split strings
cs = np.concatenate(s)
# Get params
N = len(a)
l = np.array(list(map(len,s)))
el = 2*l-1
ncols = el.max()
out = np.zeros((N,ncols),dtype=cs.dtype)
# Setup valid mask that starts at fist col until the end for each row
mask = el[:,None] > np.arange(el.max())
# Assign sepeter into valid ones
out[mask] = sep
# Setup valid mask that has True at postions where words are to be assigned
mask[:,1::2] = 0
# Assign words
out[mask] = cs
return out
示例运行 -
In [32]: a = np.array(['word', 'two words', 'and three words'])
In [33]: partitions(a, sep=' ')
Out[33]:
array([['word', '', '', '', ''],
['two', ' ', 'words', '', ''],
['and', ' ', 'three', ' ', 'words']], dtype='<U5')
In [44]: partitions(a, sep='ord')
Out[44]:
array([['w', 'ord', ''],
['two w', 'ord', 's'],
['and three w', 'ord', 's']], dtype='<U11')
方法#2
这是另一个带循环的,以节省内存 -
def partitions_loopy(a, sep):
# Get params
N = len(a)
l = np.char.count(a, sep)+1
ncols = 2*l.max()-1
out = np.zeros((N,ncols),dtype=a.dtype)
for i,(a_i,L) in enumerate(zip(a,l)):
ss = a_i.split(sep)
out[i,1:2*L-1:2] = sep
out[i,:2*L:2] = ss
return out