How to Fix: TypeError: cannot perform reduce with flexible type


One error you may encounter when using Python is:

ValueError: cannot perform reduce with flexible type

This error occurs when you attempt to perform some calculation on an object in Python that is not numeric.

The following example shows how to fix this error in practice.

How to Reproduce the Error

Suppose we have the following NumPy array:

import numpy as np

#define NumPy array of values
data = np.array(['1', '2', '3', '4', '7', '9', '10', '12'])

#attempt to calculate median of values
np.median(data)

TypeError: cannot perform reduce with flexible type

We receive a TypeError because we attempted to calculated the median of a list of string values.

How to Fix the Error

The easiest way to fix this error is to simply convert the NumPy array to a float object so that we can perform mathematical operations on it.

The following code shows how to do so:

#convert NumPy array of string values to float values
data_new = data.astype(float)

#view updated NumPy array
data_new

array([ 1.,  2.,  3.,  4.,  7.,  9., 10., 12.])

#check data type of array
data_new.dtype

dtype('float64')

We can now perform mathematical operations on the NumPy array:

#calculate median value of array
np.median(data_new)

5.5

#calculate mean value of array
np.mean(data_new)

6.0

#calculate max value of array
np.max(data_new)

12.0

Notice that we don’t receive any errors because the NumPy array is a float object, which means we can perform mathematical operations on it.

Additional Resources

The following tutorials explain how to fix other common errors in Python:

How to Fix KeyError in Pandas
How to Fix: ValueError: cannot convert float NaN to integer
How to Fix: ValueError: operands could not be broadcast together with shapes

Leave a Reply

Your email address will not be published.