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

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

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

#check data type of array


We can now perform mathematical operations on the NumPy array:

#calculate median value of array


#calculate mean value of array


#calculate max value of array


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. Required fields are marked *