如何在numpy中展平对象数组?

时间:2019-07-05 10:56:26

标签: python numpy

我有一个数组

np.array([[[ 1,  2], [ 3, -4]],[[-1,  0]]], dtype=object)

我想将其弄平以获得类似的内容:

array([1,2,3,-4,-1,0], dtype=int32)

我尝试了Flatten numpy array,但它引发了Value错误

要清楚,我的数组始终是由多个2D和1D数组组成的对象数组

4 个答案:

答案 0 :(得分:0)

如果您不知道嵌套数组的深度,可以这样做:

l = np.array([[[ 1,  2],[ 3, -4]], [-1,  0]])

from collections.abc import Iterable

def flatten(l):
    returnlist=[]
    for elem in l:
        if isinstance(elem, Iterable):
            returnlist.extend(flatten(elem))
        else:
            returnlist.append(elem)

    return returnlist

np.array(flatten(l))

如果是二维的,则可以像该帖子一样建议How to make a flat list out of list of lists

flat_list = [item for sublist in l for item in sublist]

或仅使用numpys flatten。

顺便说一句,由于使用了双括号,您的示例不是二维的,这也是为什么flatten()不起作用的原因:

np.array([ [[ 1, 2], [ 3, -4 ]] ,[[-1, 0]]], dtype=object)

答案 1 :(得分:0)

In [333]: arr = np.array([[[ 1,  2], [ 3, -4]],[[-1,  0]]], dtype=object)                                       
In [334]: arr                                                                                                   
Out[334]: array([list([[1, 2], [3, -4]]), list([[-1, 0]])], dtype=object)
In [335]: arr.shape                                                                                             
Out[335]: (2,)
In [336]: np.vstack(arr)                                                                                        
Out[336]: 
array([[ 1,  2],
       [ 3, -4],
       [-1,  0]])
In [337]: np.vstack(arr).ravel()                                                                                
Out[337]: array([ 1,  2,  3, -4, -1,  0])

答案 2 :(得分:0)

它是嵌套的,但是您可以使用sum()来做到这一点:

nested_list_values = [[[ 1,  2], [ 3, -4]],[[-1,  0]]]
sum(sum(, []), [])
  

[1、2、3,-4,-1、0]

或者,如果感觉更自然,请使用itertools.chain()

from itertools import chain

nested_list_values = [[[ 1,  2], [ 3, -4]],[[-1,  0]]]
list(chain(*chain(*nested_list_values)))
  

[1、2、3,-4,-1、0]

答案 3 :(得分:-1)

只需展平嵌套列表,您可以执行以下操作(可能比其他示例更容易理解):

def flatten_list(lst):
   if not lst:
      return []
   elif isinstance(lst[0], list):
      return flatten_list(lst[0]) + flatten_list(lst[1:])
   else:
      return [lst[0]] + flatten_list(lst[1:])
相关问题