目录
一、函数解释
二、具体示例
三、整体代码
setdiff1d(ar1, ar2, assume_unique=False)
1.功能:找到2个数组中集合元素的差异。
2.返回值:在ar1中但不在ar2中的已排序的唯一值。
3.参数:
1.assume_unique = False的情况:
a = np.array([1,2,3])
b = np.array([4,5,6])
c = np.setdiff1d(a, b)
print(c)#[1 2 3]
a = np.array([1,2,3])
b = np.array([1,2,3])
c = np.setdiff1d(a, b)
print(c)#[]
a = np.array([1,2,3])
b = np.array([2,3,4])
c = np.setdiff1d(a, b)
print(c)#[1]
a = np.array([1,2,3,4])
b = np.array([3,4,5,6])
c = np.setdiff1d(a, b)
print(c)#[1 2]
a = np.array([1,2,3,2,4,1])
b = np.array([3,4,5,6])
c = np.setdiff1d(a, b)
print(c)#[1 2]
a = np.array([8,2,3,2,4,1])
b = np.array([7,4,5,6,3])
c = np.setdiff1d(a, b)
print(c)#[1 2 8]
可以从最后看出返回的值从小到大排序,并且唯一。(8在a的第1位,2在a中重复了2次)
2.assume_unique = True的情况:
a = np.array([3,2,1])
b = np.array([4,5,6])
c = np.setdiff1d(a, b,True)
print(c)#[3 2 1]
a = np.array([8,2,3,2,4,1])
b = np.array([7,4,5,6,3])
c = np.setdiff1d(a, b,True)
print(c)#[8 2 2 1]
a = np.array([8,2,3,4,2,4,1])
b = np.array([7,9,5,6,3])
c = np.setdiff1d(a, b,True)
print(c)#[8 2 4 2 4 1]
可以看出把在a中的但是不在b中的元素按a中的顺序排序,并且不合并重复的元素,即假定输入数组也是唯一的,因此相比于False确实提升了运算速度。
import numpy as np
def main():
a = np.array([1,2,3])
b = np.array([4,5,6])
c = np.setdiff1d(a, b)
print(c)#[1 2 3]
a = np.array([1,2,3])
b = np.array([1,2,3])
c = np.setdiff1d(a, b)
print(c)#[]
a = np.array([1,2,3])
b = np.array([2,3,4])
c = np.setdiff1d(a, b)
print(c)#[1]
a = np.array([1,2,3,4])
b = np.array([3,4,5,6])
c = np.setdiff1d(a, b)
print(c)#[1 2]
a = np.array([1,2,3,2,4,1])
b = np.array([3,4,5,6])
c = np.setdiff1d(a, b)
print(c)#[1 2]
a = np.array([8,2,3,2,4,1])
b = np.array([7,4,5,6,3])
c = np.setdiff1d(a, b)
print(c)#[1 2 8]
a = np.array([3,2,1])
b = np.array([4,5,6])
c = np.setdiff1d(a, b,True)
print(c)#[3 2 1]
a = np.array([8,2,3,2,4,1])
b = np.array([7,4,5,6,3])
c = np.setdiff1d(a, b,True)
print(c)#[8 2 2 1]
a = np.array([8,2,3,4,2,4,1])
b = np.array([7,9,5,6,3])
c = np.setdiff1d(a, b,True)
print(c)#[8 2 4 2 4 1]
if __name__ == '__main__':
main()
多学习这样的函数,对数据处理很有帮助~