【问题标题】:concatenate numpy string array along an axis?沿轴连接numpy字符串数组?
【发布时间】:2015-12-15 23:24:10
【问题描述】:

我有一个二维 numpy 字符串数组。有没有办法连接每行中的字符串,然后用分隔符字符串连接生成的字符串,例如换行符?

例子:

pic = np.array([ 'H','e','l','l','o','W','o','r','l','d']).reshape(2,5)

我想得到:

"Hello\nWorld\n"

【问题讨论】:

  • 最后的\n'重要吗? join 的通常用法是在字符串之间放置分隔符,但不在末尾。
  • 这不重要 - 我以后可以随时添加。

标签: python string numpy


【解决方案1】:

在 numpy 之外做起来并不难:

>>> import numpy as np
>>> pic = np.array([ 'H','e','l','l','o','W','o','r','l','d']).reshape(2,5)
>>> pic
array([['H', 'e', 'l', 'l', 'o'],
       ['W', 'o', 'r', 'l', 'd']], 
      dtype='|S1')
>>> '\n'.join([''.join(row) for row in pic])
'Hello\nWorld'

还有np.core.defchararray 模块,它具有处理字符数组的“好东西”——但是,它指出这些只是python 内置函数和标准库函数的包装,所以你可能不会得到任何真正的加速通过使用它们。

【讨论】:

    【解决方案2】:

    你有正确的想法。这是一个 vectorized NumPythonic 实现尝试遵循这些想法 -

    # Create a separator string of the same rows as input array
    separator_str = np.repeat(['\n'], pic.shape[0])[:,None]
    
    # Concatenate these two and convert to string for final output
    out = np.concatenate((pic,separator_str),axis=1).tostring()
    

    或者使用np.column_stack 的单线 -

    np.column_stack((pic,np.repeat(['\n'], pic.shape[0])[:,None])).tostring()
    

    示例运行 -

    In [123]: pic
    Out[123]: 
    array([['H', 'e', 'l', 'l', 'o'],
           ['W', 'o', 'r', 'l', 'd']], 
          dtype='|S1')
    
    In [124]: np.column_stack((pic,np.repeat(['\n'], pic.shape[0])[:,None])).tostring()
    Out[124]: 'Hello\nWorld\n'
    

    【讨论】:

    • 这很有趣。
    • @user5402 是的!我没想到会有一个纯粹的 numpythonic 解决方案,但它最终成功了! :)
    • 这很有趣。我有点懒得尝试,但我想知道时间与其他(非 numpy)解决方案相比如何。
    【解决方案3】:

    一种方法是使用 str.join() 和列表理解,例如 -

    In [1]: import numpy as np
    
    In [2]: pic = np.array([ 'H','e','l','l','o','W','o','r','l','d']).reshape(2,5)
    
    In [3]: pic
    Out[3]:
    array([['H', 'e', 'l', 'l', 'o'],
           ['W', 'o', 'r', 'l', 'd']],
          dtype='<U1')
    
    In [4]: '\n'.join([''.join(x) for x in pic])
    Out[4]: 'Hello\nWorld'
    

    如果你真的需要最后的\n,你可以在加入字符串后将它连接起来。示例 -

    In [5]: '\n'.join([''.join(x) for x in pic]) + '\n'
    Out[5]: 'Hello\nWorld\n'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-25
      • 2018-12-13
      • 2013-11-07
      • 2022-01-22
      • 2011-06-29
      • 2011-01-22
      • 2016-12-20
      • 2017-06-03
      相关资源
      最近更新 更多