将numpy 2D数组中的字符串元素转换为array并产生3D数组 [英] Convert string elements in numpy 2D-array to array and yield a 3D-array

查看:159
本文介绍了将numpy 2D数组中的字符串元素转换为array并产生3D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个形状为(3,2)的字符串的Numpy 2D数组:

I have a numpy 2D-array of string with shape (3,2):

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

为了简化起见,我确定每个字符串的长度都相等.

To make it easier, I am sure the length of each string is equal.

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

And I have a function, i.e. namely split(), to make string '123' to python list ['1','2','3']

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

Now I would like to produce a 3D-array with '123' to an array array(['1', '2', '3']) and finally I can get a 3D-array with shape (3,2,3):

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

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

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

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

I have an idea that splitting the string to list first and write to file with numpy's format. Then, I shall read the array from the file.

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

这就是问题所在,是否有一种优雅的转换方法?

提前谢谢!

推荐答案

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

The output would simply be a view of the input and hence this would be memory-efficient. As such, the runtime would be constant (irrespective of array shape) -

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

这篇关于将numpy 2D数组中的字符串元素转换为array并产生3D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆