【问题标题】:Reduce multi-dimensional array of strings along axis in Numpy在 Numpy 中减少沿轴的多维字符串数组
【发布时间】:2018-12-13 21:39:42
【问题描述】:

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

【问题讨论】:

  • 所有元素都是单个字符吗?
  • 空间重要吗,还是''.join(s) 就足够了?
  • @Divakar 在这个例子中他们是,但我正在处理的问题涉及字符串
  • @jpp 不是精确的空间,但需要一些分隔符

标签: python arrays numpy


【解决方案1】:

这是一种您可以强制 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']

【讨论】:

  • 感谢您的回答!虽然它回答了我的问题,但我还是选择了@user3483203 的答案,因为它还带来了对不同的、可能更优化的解决方案的洞察
【解决方案2】:

使用常规字符串操作比使用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)

【讨论】:

  • 实际上更糟糕的是,arr = np.array([['a', 'b', 'c'],['e','f','g']]); np.char.join(' ', arr) 甚至都不工作...你必须强制 NumPy 将其视为列表数组才能获得相同的结果。跨度>
  • (如果您确实有一个字符串列表数组,如果需要从原始字符串数组创建它已经涉及一些开销,那么这两种方法的性能似乎是相同的.. .)
猜你喜欢
  • 2015-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-15
  • 2021-11-12
  • 2014-08-08
  • 2017-06-03
  • 2014-11-15
相关资源
最近更新 更多