numpy 数值的修改

一、步骤

1、查找值

使用数组的索引和切片

2、修改值

直接赋值

例子

import numpy as np

arr1 = np.arange(0, 24).reshape(4, 6)
# 使用数组的索引和切片查找值,并修改值
arr1[:, 2:5] = 10
print(arr1)

二、查找值补充

1、布尔索引

a、实质

判断条件做为索引使用

b、例子

import numpy as np

arr1 = np.arange(0, 24).reshape(4, 6)
# 找到值
print(arr1 < 10)
# 修改值
arr1[arr1 < 8] = 0
print(arr1)

2、三元运算

a、格式

np.where(条件, x, y)
# 数组中符合条件(布尔索引)的赋值x,不符合的赋值y

注意:np.where()方法,有返回值,需要一个变量去接收返回值

b、例子

import numpy as np

arr1 = np.arange(0, 24).reshape(4, 6)
arr2 = np.where(arr1 < 10, 0, 1)
print(arr2)

3、clip(裁剪)

a、格式

np.clip(a, min, max)
# a 是数组
# min 数组a中元素小于min的用min赋值
# max 数组a中元素大于max的用max赋值

注意:np.clip()方法,有返回值,需要一个变量去接收返回值

b、例子

import numpy as np

arr1 = np.arange(0, 24).reshape(4, 6)
print(arr1)
print('=' * 40)
arr2 = np.clip(arr1, 5, 10)
print(arr2)
原文地址:https://www.cnblogs.com/wt7018/p/11954810.html