1

I have the following three numpy arrays:

a = np.array([ 1, 2, 3, 4, 2, 3, 4 ])
b = np.array([ [1], [2,3,4], [], [2,3,4] ])
c = np.array([ 1, [2,[3,4]], [], [2,3,4] ])

How can I use a single function f that would work on all three arrays, returning the values in all sublists, in unaltered order and unaltered type?

So the answer should be f(a) == f(b) == f(c) == a.

I found the following trick here (Concatenation of inner lists or ints):

def f(b):
    np.array([a for x in np_array for a in (x if isinstance(x, list) else [x])])

But this does not work for array c.

3
  • 1
    Possible typo? You need a return statement in def f(b). Commented Jul 8, 2014 at 16:10
  • Indeed some typos: missing return statement, and c = np.array([ [1], [2,[3,4]], [], [2,3,4] ]) Commented Jul 8, 2014 at 16:12
  • If you don't care about element-wise comparison, then you could implement something like this generator solution: stackoverflow.com/a/2158532/1634191 Commented Jul 8, 2014 at 16:21

3 Answers 3

2

For those who don't need to handle nesting, ndarray.flatten does the trick.

For your use case, I'm not aware of a numpy solution, but here is a pure python alternative:

>>> b = np.array([ [1], [2,3,4], [], [2,3,4] ])
>>> from compiler.ast import flatten
>>> np.array(flatten(b))
array([1, 2, 3, 4, 2, 3, 4])

It will only work on python 2.

For python 3 try this:

from collections import Iterable

def flatten(collection):
  for element in collection:
    if isinstance(element, Iterable) and not isinstance(element, str):
      for x in flatten(element):
        yield x
    else:
      yield element

def flatten_array(array):
    return np.array(flatten(array))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the solution with generators. However, it does not seem to work. It does never eneter the for element in collection loop (I placed a print statement in there, which I don't see back). Should I somehow call the flatten generator inan iterative way? How is this done?
1

In Python3 there is an inbuild function flatten() for that

import numpy as np
arr=np.array([[4,7,-6],[3,0,8],[2,0,-4]])
print(arr)
print(arr.flatten())

Comments

0

ravel() method is more efficient than all

import numpy as np
a = np.array([[1,2,3],[4,5,6]])
print(a.ravel())# flattened array

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.