Numpy数据分析练习(11-20)

Numpy数据分析问答

11、如何获取两个numpy数组之间的公共项?

#given
a = np.array([1,2,3,2,3,4,3,4,5,6])
b = np.array([7,2,10,2,7,4,9,4,9,8])
#aspect output
array([2, 4])
#solution
np.intersect1d(a,b)

12、如和从一个数组中删除存在于另一个数组中的项。

#given
a = np.array([1,2,3,4,5])
b = np.array([5,6,7,8,9])
#aspect output
np.setdiff1d(a,b)

13、如何得到两个数组元素匹配的位置?

问题:获取a 和 b元素匹配的位置

a = np.array([1,2,3,2,3,4,3,4,5,6])
b = np.array([7,2,10,2,7,4,9,4,9,8])
#aspect output
# > (array([1, 3, 5, 7]),)
np.where(a == b)

14、如何从numpy数组中提取给定范围内的所有数字?

问题:获取5到10之间的所有项目。

a = np.arange(15)
#method 1
index = np.where((a >= 5) & (a <= 10))
a[index]
#method 2
index = np.where(np.logical_and(a >= 5, a <= 10))
a[index]
#method 3
a[(a >= 5) & (a <= 10)]

15、如何创建一个python函数来处理scalars并在numpy数组上工作?

问题:转换适用于两个标量的函数 maxx, 1以处理两个数组

#given
def maxx(x, y):
	'''Get the maximun of two items'''
	if x > y:
		return x
	else:
		return y
maxx(1, 5)
# > 5
#aspect output
a = np.array([5, 7, 9, 8, 6, 4, 5])
b = np.array([6, 3, 4, 8, 9, 7, 1])
pair_max(a, b)
# > array([ 6.,  7.,  9.,  8.,  9.,  7.,  5.])
#solution
pair_max = np.vectorize(maxx, otypes = [float])
a = np.array([5, 7, 9, 8, 6, 4, 5])
b = np.array([6, 3, 4, 8, 9, 7, 1])

pair_max(a, b)
# > array([ 6.,  7.,  9.,  8.,  9.,  7.,  5.])

16、如何交换二维numpy数组中的两列?

问题:在数组arr中交换列1和列2.

#given
arr = np.arange(9).reshape(3,3)
#solution
arr[:,[1,0,2]]
#output
# > array([[1, 0, 2],
# >        [4, 3, 5],
# >        [7, 6, 8]])

17、如何交换二维数组中的两行?

问题:交换数组arr中的第1和第2行:

#given
arr = np.arange(9).reshape(3,3)
# solution
arr[[1,0,2], :]
#output
# > array([[3, 4, 5],
# >        [0, 1, 2],
# >        [6, 7, 8]])

18、如何反转二维数组的行?

问题:反转二维数组arr的行。

#input
arr = np.arange(9).reshape(3,3)
#solution
arr[::-1]
#output
array([[6, 7, 8],
       [3, 4, 5],
       [0, 1, 2]])

19 、如何反转二维数组中列?

问题:反转二维数组arr的列。

#input
arr = np.arange(9).reshape(3,3)
#solution
arr[:,::-1]
#output
# > array([[2, 1, 0],
# >        [5, 4, 3],
# >        [8, 7, 6]])

20、如何创建包含5到10之间随机浮动的二维数组?

问题:问题:创建一个形状为5x3的二维数组,以包含5到10之间的随机十进制数。

#input
arr = np.arange(9).reshape(3,3)
#solution 1
rand_arr = np.random.random(low = 5, high = 10, size = (5,3)) + np.random.random((5,3))
#solution 2
rand_arr = np.random.uniform(5,10, size = (5,3))
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值