Home > other >  Find most frequent value in an np.array gives back "TypeError: cannot cast array data from dtyp
Find most frequent value in an np.array gives back "TypeError: cannot cast array data from dtyp

Time:12-21

In my project I'm creating an np.array like this:

values_array = np.array(0.00, dtype=np.float32)

After that I append more value in it during a while loop:

values_array = np.append(values_array, round(value, 2))

And this is how my final array's output looks like:

[0. 0.41 0.41 0.42 0.41 0.43]

But when I try to find the most frequent value in the array like this:

top_value = np.argmax(np.bincount(values_array))

I get this error:


TypeError: cannot cast array data from dtype('float64) to dtype('int64') according to safe rule

How can I avoid it?

CodePudding user response:

This is called mode doc. You can do this in different ways, one using the module scipy and the other using statistics.

from scipy import stats as st
st.mode(values_array)

or

import statistics as st
print(st.mode(values_array))
  • Related