Numpy 是否实现了一些减少多维字符串数组的功能?我知道它提供了一些用于多个数组的字符串连接的功能,但我还没有找到任何关于字符串缩减的信息。
假设我有一个二维字符串数组:
np.array([['a', 'b', 'c'],['e','f','g']])
我想把它转换成:
np.array(['a b c','e f g'])
有没有比使用 for 循环更好的方法,例如:
old_strings = np.array([['a', 'b', 'c'],['e','f','g']])
new_strings = np.array([])
for s in old_strings:
new_strings = np.append(new_strings, (' '.join(s)))
最佳答案
使用常规字符串操作优于使用 np.char.join
。
>>> arr = np.array([['a', 'b', 'c'],['e','f','g']])
>>> np.array([' '.join(i) for i in arr])
array(['a b c', 'e f g'], dtype='<U5')
会比np.char.join
%timeit np.array([' '.join(i) for i in arr])
8.69 µs ± 30 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit np.char.join(' ', arr)
14.6 µs ± 86.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
在更大的阵列上:
arr = np.repeat(arr, 10000).reshape(-1, 3)
%timeit np.array([' '.join(i) for i in arr])
54.2 ms ± 596 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit np.char.join(' ', arr)
72.3 ms ± 2.36 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
关于python - 在 Numpy 中沿轴减少多维字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51190740/