【numpy】np.where() + np.unique()的使用

1、np.where()的使用

有两种用法:

  • np.where(condition, x, y):当condition为True时,返回x,否则返回y
# 例1, x,y为int值
a = np.arange(10)
# array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
print(np.where(a > 5, 1, -1))
# array([-1, -1, -1, -1, -1, -1,  1,  1,  1,  1]) 
"""
例2:x, y也可以是数组,三个维度要相同,根据condition对应位置的bool值选择x和y对应位置的值
"""
np.where([[True,False], [True,True]],   
			 [[1,2], [3,4]],
             [[9,8], [7,6]])
# 输出 array([[1, 8], [3, 4]])

  • np.where(condition):返回满足condition条件的数组的索引值,多维数组会以元组形式给出。
""" 例1:一维数组 """
a = np.array([2,4,6,8,10])
np.where(a > 5)			
# (array([2, 3, 4]),)   返回索引值
a[np.where(a > 5)]  			
#array([ 6,  8, 10]) 返回元素值,即a[索引]
""" 例2:二维数组 """
a = array([[0., 1.],
  	       [0., 1.],
  	       [0., 1.],
  	       [0., 1.],
  	       [0., 1.],
  	       [0., 1.],
  	       [0., 1.],
  	       [0., 1.],
  	       [1., 0.],
  	       [0., 1.],
  	       [0., 1.],
  	       [0., 1.],
  	       [1., 0.],
  	       [1., 0.],
  	       [0., 1.],
  	       [0., 1.],
  	       [1., 0.],
  	       [0., 1.],
  	       [1., 0.],
  	       [0., 1.]])
np.where(a == 1)
# (array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,17, 18, 19], dtype=int64),
# array([1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1], dtype=int64))


2、np.unique()的使用

  • 该函数可以返回数组或列表的唯一元素(即去除重复元素),并返回对unique的元素从小到大排序后的数组。基本使用形式为:
res[, indices]=numpy.unique(arr[, return_index, return_inverse, return_counts])
  • arr:输入数组
  • return_index:如果为 true,返回输出数组res在输入数组arr中出现的第一个位置(下标),并以列表形式存储,维度与res同。
  • return_inverse:如果为true,返回输入数组arr在输出数组res中出现的位置(下标),并以列表形式存储,维度与arr同。
  • return_counts:如果为 true,返回res中的元素在原数组arr中的出现次数。
import numpy as np
A = [1, 2, 2, 5, 3, 4, 3]
a = np.unique(A)
print(a)
print("______")

a, indices = np.unique(A, return_index=True)   # 返回输出数组res在输入数组arr中出现的第一个位置(下标)
print(a)		 # 列表
print(indices)	 # 下标
print("______")

a, indices = np.unique(A, return_inverse=True)   # 返回输入数组arr在输出数组res中出现的位置(下标)
print(a)
print(indices)
print(a[indices])     # 使用下标重构原数组
print("______")

a, indices = np.unique(A, return_counts=True)    # 返回res中的元素在原数组arr中的出现次数。
print(a)
print(indices)
print("______")

B = ([1, 2], [2, 5], [3, 4])
b = np.unique(B)
C= ['fgfh','asd','fgfh','asdfds','wrh']
c= np.unique(C)
print(b)
print(c)

结果如下:

[1 2 3 4 5]
______
[1 2 3 4 5]
[0 1 4 5 3]
______
[1 2 3 4 5]
[0 1 1 4 2 3 2]
[1 2 2 5 3 4 3]
______
[1 2 3 4 5]
[1 2 2 1 1]
______
[1 2 3 4 5]
['asd' 'asdfds' 'fgfh' 'wrh']

参考链接:
np.where()的详解及代码应用
【Python】np.unique() 介绍与使用

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值