【853】numpy里面替换值
参考:How to Replace Elements in NumPy Array (3 Examples)
You can use the following methods to replace elements in a NumPy array:
Method 1: Replace Elements Equal to Some Value
#replace all elements equal to 8 with a new value of 20 my_array[my_array == 8] = 20
Method 2: Replace Elements Based on One Condition
#replace all elements greater than 8 with a new value of 20 my_array[my_array > 8] = 20
Method 3: Replace Elements Based on Multiple Conditions
#replace all elements greater than 8 or less than 6 with a new value of 20 my_array[(my_array > 8) | (my_array < 6)] = 20
The following examples show how to use each method in practice with the following NumPy array:
import numpy as np #create array my_array = np.array([4, 5, 5, 7, 8, 8, 9, 12]) #view array print(my_array) [ 4 5 5 7 8 8 9 12]
Method 1: Replace Elements Equal to Some Value
The following code shows how to replace all elements in the NumPy array equal to 8 with a new value of 20:
#replace all elements equal to 8 with 20 my_array[my_array == 8] = 20 #view updated array print(my_array) [ 4 5 5 7 20 20 9 12]
Method 2: Replace Elements Based on One Condition
The following code shows how to replace all elements in the NumPy array greater than 8 with a new value of 20:
#replace all elements greater than 8 with 20 my_array[my_array > 8] = 20 #view updated array print(my_array) [ 4 5 5 7 8 8 20 20]
Method 3: Replace Elements Based on Multiple Conditions
The following code shows how to replace all elements in the NumPy array greater than 8 or less than 6 with a new value of 20:
#replace all elements greater than 8 or less than 6 with a new value of 20 my_array[(my_array > 8) | (my_array < 6)] = 20 #view updated array print(my_array) [20 20 20 7 8 8 20 20]
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
2021-07-06 【600】Attention U-Net 解释
2021-07-06 【599】keras.layers 里面 Multiply、multiply & Add、add 的区别
2021-07-06 【598】解决 Keras 保存模型无法加载使用的问题
2018-07-06 【329】word 替换文本高级用法