numpy: where函数、集合操作

where函数

where函数是三元表达式 x if condition else y的向量版本。
通过where函数,可以批量地或者单个地对数组中元素进行替换

举个栗子,有两个数值数组x, y。另外有一个布尔型数组cond。
我们想要建立一个新数组,当cond中元素为True时,取x中的对应元素的值,反之取y中对应的元素。
我们可以这样做:

import numpy as np
x = np.array([1, 3, 5])
y = np.array([2, 4, 6])
cond = np.array([True, False, True])
res = np.where(cond, x, y)
print(res)       # [1 4 5]

注意:where函数中的x, y的顺序不能随意调换,否则逻辑是反的.

.

再举个栗子,有一个数组arr。我们想把arr中所有负数替换为0,正数不变。`

import numpy as np
arr = np.random.randn(10)
print(arr)
# [ 0.79087621  1.49431628  1.03783014 -1.68999181 -2.25265621  1.17983325
#   0.86310892  0.18541012  0.83924824  0.78316047]
arr = np.where(arr < 0, 0, arr)
print(arr)
# [0.79087621 1.49431628 1.03783014 0.         0.         1.17983325
#  0.86310892 0.18541012 0.83924824 0.78316047]

.

集合操作

常见的集合操作有:交集、并集、集合差、异或、包含关系
基础概念再解释也没什么意思,直接上代码叭:

import numpy as np
x = [1, 3, 5, 6]
y = [2, 3, 4, 6]
print(np.intersect1d(x, y))  # 求x和y的交集
# [3 6]
print(np.union1d(x, y))      # 求x和y的并集
# [1 2 3 4 5 6]
print(np.in1d(x, y))         # 判断x中的元素是否包含在y中
# [False  True False  True]
print(np.setdiff1d(x, y))    # 差集(在x中但不在y中的元素)
# [1 5]
print(np.setxor1d(x, y))     # 异或集,在x,y中 但不属于x,y交集的元素
# [1 2 4 5]

值得一提的是,集合操作返回的数组都是排序后的。

除此之外,还有一种类似于python中set集合操作的方法:unique
该方法返回数组中唯一值排序后形成的数组。

import numpy as np
x = [1, 3, 5, 6, 5, 3, 9]
print(np.unique(x))  # [1 3 5 6 9]

参考资料

《利用python进行数据分析》

发布了19 篇原创文章 · 获赞 1 · 访问量 781

猜你喜欢

转载自blog.csdn.net/weixin_43901558/article/details/104767957