首页 > 解决方案 > 如何计算同时具有字符串和整数的一维 numpy 数组的平均值

问题描述

我创建了一个 numpy 数组,

my_array = np.array([1,2,3,4,'qwerty',7,1,4,'qwerty'])

我想用这个数组的平均值替换 qwerty,那么如果 string 和 int 混合,我将如何计算平均值?我已经试过这个并且给出了一个错误

new_array = my_array[my_array != 'qwerty'].mean()

但这给出了错误 cannot perform reduce with flexible type

标签: numpy

解决方案


取平均值时,您还需要将剩余数据转换为浮点数或整数。删除字符串后,您可以.astype(float)在数组上使用来完成此操作。要替换qwerty为均值,您还需要确保将均值放在数组中的正确位置。尝试这个:

my_array = np.array([1,2,3,4,'qwerty',7,1,4,'qwerty'])

new_array=np.copy(my_array) #Create a copy of your array

#calculate the mean and put it into the array where 'qwerty' is true
new_array[my_array == 'qwerty'] = np.mean(my_array[my_array != 'qwerty'].astype(float))

输出:

array(['1', '2', '3', '4', '3.142857142857143', '7', '1', '4',
   '3.142857142857143'], dtype='<U21')

推荐阅读