目录
一、函数解释
setdiff1d(ar1, ar2, assume_unique=False)
1.功能:找到2个数组中集合元素的差异。
2.返回值:在ar1中但不在ar2中的已排序的唯一值。
3.参数:
- ar1:array_like 输入数组。
- ar2:array_like 输入比较数组。
- assume_unique:bool。如果为True,则假定输入数组是唯一的,即可以加快计算速度。 默认值为False。
二、具体示例
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()
-
多学习这样的函数,对数据处理很有帮助~
文章来源: nickhuang1996.blog.csdn.net,作者:悲恋花丶无心之人,版权归原作者所有,如需转载,请联系作者。
原文链接:nickhuang1996.blog.csdn.net/article/details/89916399