where 函数筛选位置,并进行矩阵内容修改/索引获取

该博客探讨了如何使用numpy库中的where函数来筛选多维矩阵中特定位置的元素,并对其进行修改。示例代码展示了筛选大于5的值并将其替换为2的过程,同时通过循环遍历每一列获取符合条件的索引及其对应矩阵内容。
摘要由CSDN通过智能技术生成

where 函数筛选位置,并进行矩阵内容修改

import numpy as np

wtcam=[[[1,0],
       [6,0],
       [1,0],
       [1,0]],
       [[1,0],
       [1,0],
       [1,0],
       [1,0]],
       [[1,0],
       [6,0],
       [1,0],
       [6,0]]]
wtcam=np.array(wtcam)
print("矩阵维度")
print(np.shape(wtcam))

temp_list= np.where(wtcam[:, :, 0] > 5) 
print("符合条件的位置索引")
print(temp_list)
print("获取位置索引对应的矩阵值")
print(wtcam[temp_list])
print("修改位置索引对应的矩阵值,输出")
wtcam[temp_list] = 2
print(wtcam) 

对应输出:

矩阵维度
(3, 4, 2)
符合条件的位置索引
(array([0, 2, 2]), array([1, 1, 3]))
获取位置索引对应的矩阵值
[[6 0]
 [6 0]
 [6 0]]
修改位置索引对应的矩阵值,输出
[[[1 0]
  [2 2]
  [1 0]
  [1 0]]

 [[1 0]
  [1 0]
  [1 0]
  [1 0]]

 [[1 0]
  [2 2]
  [1 0]
  [2 2]]]
#能够看到检索前两维度后,修改了第三维度所有的值

where 函数筛选位置,并进行矩阵索引获取

import numpy as np

wtcam=[[[1,0],
       [6,0],
       [1,0],
       [1,0]],
       [[1,0],
       [1,0],
       [1,0],
       [1,0]],
       [[1,0],
       [6,0],
       [1,0],
       [6,0]]]
wtcam=np.array(wtcam)
print("矩阵维度")
print(np.shape(wtcam))

temp = []
for i in range(0,np.shape(wtcam)[1]):
    pos = np.where(wtcam[:, i, 0] > 5)  #固定类找时序片段索引,返回元组
    print("单次获取的索引为:")
    print(pos)
    print("获取索引对应矩阵内容")
    print(wtcam[pos])   #[?<400, ?<20, 2]

    temp.append(pos)
    print(type(pos))
print("获取的全部索引为:")
print(temp)
print("全部索引长度:")
print(len(temp))

print(type(temp[0]))   #元组
print(type(np.array(temp[0]))) #np数组

对应输出为:

矩阵维度
(3, 4, 2)
单次获取的索引为:
(array([], dtype=int64),)
获取索引对应矩阵内容
[]
<class 'tuple'>
单次获取的索引为:
(array([0, 2]),)
获取索引对应矩阵内容
[[[1 0]
  [6 0]
  [1 0]
  [1 0]]

 [[1 0]
  [6 0]
  [1 0]
  [6 0]]]
<class 'tuple'>
单次获取的索引为:
(array([], dtype=int64),)
获取索引对应矩阵内容
[]
<class 'tuple'>
单次获取的索引为:
(array([2]),)
获取索引对应矩阵内容
[[[1 0]
  [6 0]
  [1 0]
  [6 0]]]
<class 'tuple'>
获取的全部索引为:
[(array([], dtype=int64),), (array([0, 2]),), (array([], dtype=int64),), (array([2]),)]
全部索引长度:
4
<class 'tuple'>
<class 'numpy.ndarray'>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值