Python 减少Numpy中沿轴的多维字符串数组

Python 减少Numpy中沿轴的多维字符串数组,python,arrays,numpy,Python,Arrays,Numpy,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_strin

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)))

这是一种强制NumPy API执行此操作的方法,尽管它可能与您自己执行此操作没有太大区别:

import numpy as np

# Make one-dimensional array of lists of strings
a = np.array([None, None])
a[0] = ['a', 'b', 'c']
a[1] = ['e', 'f', 'g']
# Join
print(np.char.join(' ', a))
>>> ['a b c' 'e f g']

使用常规字符串操作优于使用
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')
在更大的阵列上:

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)

所有元素都是单个字符吗?空格重要吗?还是
'.join(s)
就足够了?@Divakar在本例中它们是,但我正在处理的问题涉及characters@jpp确切地说不是空格,但需要一些分隔符来回答!虽然它回答了我的问题,但我还是选择了@user3483203的答案,因为它也带来了不同的、可能是更优的解决方案的见解,实际上有点糟糕,
arr=np.array([[a',b',c',['e','f','g']);np.char.join(“”,arr)
甚至不起作用。。。你必须强迫NUMPY考虑它是一个列表数组以得到相同的结果。(如果你有一个字符串列表数组,如果需要从原始字符串数组中创建它,那么它已经包含了一些开销,那么这两种方法的性能似乎是相同的…)
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)