python - 在 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_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/

相关文章:

python - 为什么 conda install tk 在我的 docker 容器中不起作用,即使它说已安装?

python - 如何将 bash 变量传递到文件中

python - 在 Ubuntu 上使用带有 SpatiaLite 的 GeoDjango 时出错

node.js - 如何在不使用 unwind 的情况下使用 mongodb 中的数组元素对数据进行排序

c - 防止c中字符数组溢出

arrays - 对图像进行积分的有效方法

python - Pandas groupby、loc、forloop 和条件语句

python - 有没有一种有效的方法可以将 numpy.ndarray 转换为列表?

arrays - iOS12 中的 NSKeyedUnarchiver 更改 - 如何取消存档字符串数组

python - 将 DatetimeIndex 转换为日期时间