alex_bn_lee

导航

< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

统计

【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]

 

posted on   McDelfino  阅读(57)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 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 替换文本高级用法
点击右上角即可分享
微信分享提示