1 python数据分析numpy基础之union1d求数组并集
python的numpy库的union1d(x,y)函数,计算x和y的并集,并返回去重后的有序结果。
用法
numpy.union1d(ar1, ar2)
描述
numpy.union1d()计算两个数组的并集,并且返回去重后的有序结果。
入参
ar1,ar2:必选,列表、元组、数组;如果是多维则自动转一维数组;
1.1 入参ar1和ar2
numpy.intersect1d()的入参ar1和ar2,为必选入参,可以为数组、列表、元组。如果是多维数组,将会转换为一维数组后,进行处理。
>>> import numpy as np
# union1d()返回两个数组的并集,并去重和排序
# 入参ar1/ar2为列表
>>> np.union1d([-2,1,0,3,5],[2,-1,6,9,2])
array([-2, -1, 0, 1, 2, 3, 5, 6, 9])
# 入参ar1/ar2为元组
>>> np.union1d((-2,1,0,3,5),(2,-1,6,9,2))
array([-2, -1, 0, 1, 2, 3, 5, 6, 9])
# 入参ar1/ar2为数组
>>> np.union1d(np.array((-2,1,0,3,5)),np.array((2,-1,6,9,2)))
array([-2, -1, 0, 1, 2, 3, 5, 6, 9])
# 入参ar1/ar2为二维数组转为一维数组,再求并集,并去重排序
>>> np.union1d([[3,5,2,6],[0,2,5,8]],[[1,3,5,9],[0,2,6,8]])
array([0, 1, 2, 3, 5, 6, 8, 9])
1.2 计算多个数组的并集
python的functools.reduce(func,可迭代对象)函数,对可迭代对象累计调用func。比如,从可迭代对象取出前2个元素,传给func()并调用,再将输出结果与第3个元素传给func()并调用,依次类推,直到迭代对象的每个元素的取完。
通过reduce()和union1d()计算多个数组的并集。
>>> import numpy as np
# reduce(func,seq)对seq的每个元素电影func
# 用reduce 多次调用union1d 求3个元组的并集
>>> from functools import reduce
>>> reduce(np.union1d,([-3,2,5,6],[2,6,8,0],[1,5,9,10]))
array([-3, 0, 1, 2, 5, 6, 8, 9, 10])