正确有效的方法来平坦化python中的numpy中的数组? [英] correct and efficient way to flatten array in numpy in python?

查看:345
本文介绍了正确有效的方法来平坦化python中的numpy中的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有:

a = array([[1,2,3],[4,5,6]])

,我想将其扁平化,将两个内部列表连接到一个平面数组条目中.我可以做到:

and I'd like to flatten it, joining the two inner lists into one flat array entry. I can do:

array(list(flatten(a)))

但是由于列表强制转换(我想以数组而不是生成器结尾),所以效率似乎很低.

but that seems inefficient due to the list cast (I want to end up with an array and not a generator.)

此外,如何将其概括为这样的数组:

Also, how can this be generalized to an array like this:

b = array([[[1,2,3],[4,5,6]], [[10,11,12],[13,14,15]]])

结果应为:

b = array([[1,2,3,4,5,6],
           [10,11,12,13,14,15]])

是否有内置/高效的numpy/scipy运算符?谢谢.

are there builtin/efficient numpy/scipy operators for this? thanks.

推荐答案

您可以使用 reshape方法.

You can use the reshape method.

>>> import numpy
>>> b = numpy.array([[[1,2,3],[4,5,6]], [[10,11,12],[13,14,15]]])
>>> b.reshape([2, 6])
array([[ 1,  2,  3,  4,  5,  6],
       [10, 11, 12, 13, 14, 15]])

这篇关于正确有效的方法来平坦化python中的numpy中的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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