1

I have few numpy arrays, which can be formatted as

[1.525, 2.565, 6.367, ...]  # elements are float numbers

or

['', '', '', ...]  # elements are empty strings

I'd like to find out if all the elements in an array are of the same data type.

For now, I am using:

if isinstance(np.any(time_serie),float):
    return sum(time_serie)

But this one doesn't work. I got following error:

TypeError: cannot perform reduce with flexible type

So, may I know how to work around this? Thanks.

2
  • 7
    You can check the dtype of the array. If it isn't object, then they're all the same type. If it is object, then you've got more work to do... Commented Mar 10, 2014 at 15:50
  • @mgilson's comment is better than my answer with respect to numpy arrays. My answer is a generic solution for possibly heterogeneous sequences. Commented Mar 10, 2014 at 15:52

2 Answers 2

2

If you're looking for a particular data-type as provided in your example, e.g. all items are floats, then a map and reduce will do the trick:

>>> x = [1.525, 2.565, 6.367]

>>> all(map(lambda i: isinstance(i, float), x))
    True

>>> x = [1.525, 2.565, '6.367']

>>> all(map(lambda i: isinstance(i, float), x))
    False
Sign up to request clarification or add additional context in comments.

2 Comments

This can be greatly simplified to all(isinstance(i, float) for i in x).
Agreed, all would simplify.
0

You might want to use a list comprehension or map() for creating a sequence of data types, then make a set from this sequence and see if the length of the set is 1.

2 Comments

Arguably, there's no need to go through the whole structure, he just needs the answer, which is apparent at the first item which does not fit. all(isinstance(elem, float) for elem in someIterable)
That is right, but in his special case mgilson's approach to check for dtype not being object is still the most efficient shortcut :-)

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.