1

I have a numpy array as the following:

import numpy as np
arr = np.array([np.array([1]),np.array([1,2]),np.array([1,2,3]),np.array([1,3,4,2,4,2])])

I want a nice numpy function, which gives me the maximum length of the arrays inside my arr array. So I need a numpy function, which return for this example 6.

This is possible with iteration, but I am looking for a nicer way, perhaps even without map()

Any function inside tensorflow or keras would also be possible to use.

10
  • 1
    Your "array" is not an array, it's a Python list, and that particular list has no way of being transformed in any straightforward way into a numpy array (irregular dimension). Commented Sep 3, 2020 at 8:44
  • 3
    max(len(a) for a in arr)? Also, arr can't be a numpy array, only with dtype=object. Commented Sep 3, 2020 at 8:45
  • Error on my side, I forgot the np.array constructor, I just updated my post Commented Sep 3, 2020 at 8:48
  • 1
    What are the advantages you get by transforming it all to np.arrays? I don't see any. Commented Sep 3, 2020 at 8:49
  • 1
    @MichaelJanz: The answer was wrong. It counted the sum of the elements.Applied to arr = [[9999],[2,2,2,2,2],[1,1]] it would have returned 1. Commented Sep 3, 2020 at 9:12

3 Answers 3

3

We could do:

max(map(len, arr))
#6
Sign up to request clarification or add additional context in comments.

3 Comments

OP: "This is possible with iteration, but I am looking for a nicer way, perhaps even without map()"
I think We have to use map or loop here
Agreed. But the OP probably wants to know whether an accelerated implementation exists. Possibly an API either with low level language access or with GPU support
1

Another simple trick is to use max() function with key argument to return the array with maximum length.

len(max(arr, key = len))

Comments

0

Another way would be to use the keras.preprocessing.sequence.pad_sequences() function.

It pads the sequences to the lenght of the maximum, but in my opinion it creates a high memory usage and depending on the array it might take some time. However, this would be a way without looping:

len(keras.preprocessing.sequence.pad_sequences(arr)[0])

2 Comments

I expect this to be much slower than simple looping over array.
As I said in my answer, yes

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.