如何修复类型错误:不能用灵活的类型执行还原操作

231 阅读1分钟

在使用Python时,你可能遇到的一个错误是:

ValueError: cannot perform reduce with flexible type

当你试图在Python中对一个不是数字的对象进行一些计算时,这个错误就会发生。

下面的例子显示了如何在实践中解决这个错误。

如何重现这个错误

假设我们有以下NumPy数组:

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

我们收到一个TypeError,因为我们试图计算一个字符串值列表的中位数。

如何修复该错误

解决这个错误的最简单的方法是将NumPy数组转换为浮点对象,这样我们就可以对其进行数学运算。

下面的代码显示了如何做到这一点:

#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')

我们现在可以对NumPy数组进行数学运算了:

#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

注意,我们没有收到任何错误,因为NumPy数组是一个浮点对象,这意味着我们可以对它进行数学运算。

其他资源

下面的教程解释了如何修复Python中的其他常见错误:

如何修复Pandas中的KeyError
如何修复。ValueError: 无法将浮点数NaN转换为整数
如何修复。ValueError:操作数不能与形状一起广播