【问题标题】:Convert string elements in numpy 2D-array to array and yield a 3D-array将 numpy 2D 数组中的字符串元素转换为数组并生成 3D 数组
【发布时间】:2018-01-09 07:46:35
【问题描述】:

我有一个 numpy 二维字符串数组,形状为 (3,2)

ar_2d = array([['123', '456'],
               ['789', '0ab'],
               ['cde', 'fgh']],
              dtype='<U3')

为了方便起见,我确定每个字符串的长度是相等的。

我有一个函数,即split(),将字符串'123' 转换为python 列表['1','2','3']

现在我想用'123' 生成一个3D 数组到一个数组array(['1', '2', '3']),最后我可以得到一个形状为(3,2,3) 的3D 数组:

ar_3d = array([[['1', '2', '3'],
                ['4', '5', '6']],

                [['7', '8', '9'],
                 ['0', 'a', 'b']],

                [['c', 'd', 'e'],
                 ['f', 'g', 'h']]],
               dtype='<U1')

我有一个想法,首先将字符串拆分为列表,然后以 numpy 的格式写入文件。然后,我将从文件中读取数组。

如果元素是整数,会更容易吗?即编号123 列出[1,2,3]

那么问题来了,有没有一种优雅的方法来进行转换?

提前致谢!

【问题讨论】:

  • 发布的解决方案对您有用吗?有关如何处理解决方案的更多信息 - stackoverflow.com/help/someone-answers
  • @Divakar 您的解决方案是最好的解决方案!再次感谢您。

标签: python numpy multidimensional-array


【解决方案1】:

使用ndarray.view查看U1,然后reshape成3D -

In [15]: a
Out[15]: 
array([['123', '456'],
       ['789', '0ab'],
       ['cde', 'fgh']], 
      dtype='<U3')

In [16]: a.view('U1').reshape(a.shape + (-1,))
Out[16]: 
array([[['1', '2', '3'],
        ['4', '5', '6']],

       [['7', '8', '9'],
        ['0', 'a', 'b']],

       [['c', 'd', 'e'],
        ['f', 'g', 'h']]], 
      dtype='<U1')

输出只是输入的视图,因此这将节省内存。因此,运行时间将是恒定的(与数组形状无关)-

In [20]: %timeit a.view('U1').reshape(a.shape + (-1,))
1000000 loops, best of 3: 828 ns per loop

In [21]: a_big = np.tile(a,10000)

In [22]: %timeit a_big.view('U1').reshape(a_big.shape + (-1,))
1000000 loops, best of 3: 851 ns per loop

【讨论】:

    猜你喜欢
    • 2021-12-29
    • 2019-10-31
    • 2017-07-26
    • 1970-01-01
    • 1970-01-01
    • 2016-03-24
    • 2017-07-27
    • 1970-01-01
    • 2021-05-27
    相关资源
    最近更新 更多