numpy - 如何计算同时具有字符串和整数的一维 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
解决方案
取平均值时,您还需要将剩余数据转换为浮点数或整数。删除字符串后,您可以.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')
推荐阅读
- javascript - 为什么这个javascript验证总是失败
- azure - 使用 powershell 通过 ftp 上传文件及其子目录
- azure - 使用 Azure 功能从 ServiceBus 主题/订阅读取时出错
- deployment - 如何将 2 个应用程序(同一个耳朵)部署到不同端口上的单个 jboss。甚至可能吗?
- node.js - NodeJs & Socket.IO 回合制多人游戏,关于配对玩家的问题
- openedge - 如何计算进行中/开放边缘 4 周期间的每周平均销售额?
- sql - oracle中REGEXP_LIKE的反义词是什么
- javascript - Vue v-for 在新文本区域上自动对焦
- javascript - 如何在 ReactJS 组件对象数组中插入元素(在现有元素之间)
- c++ - Qt Drop 事件未触发