本文介绍了在python中将numpy中的数组展平的正确有效的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有:
a = array([[1,2,3],[4,5,6]])
我想将其展平,将两个内部列表合并为一个平面数组条目.我可以:
array(list(flatten(a)))
但由于列表转换,这似乎效率低下(我想以数组而不是生成器结束.)
此外,如何将其推广到这样的数组:
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 运算符?谢谢.
解决方案
您可以使用 reshape
方法.
I have:
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]]])
where the result should be:
b = array([[1,2,3,4,5,6],
[10,11,12,13,14,15]])
are there builtin/efficient numpy/scipy operators for this? thanks.
解决方案
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中的数组展平的正确有效的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!