Numpy--创建各类数组及其unique函数

以下代码均需要导入numpy,故省略 import numpy as np

1、基本操作:

import numpy as np

a = np.array([1, 2, 3])
print(a)
print(type(a))  # 查看数组类型
print(a.shape)  # 查看大小

# 通过使用reshape明确将数组指定行列关系
b = a.reshape(1, -1)   # 第一个1表示整个数组只有一行,后面的-1是占位符,实际表示的是3
print(b.shape)

结果为:

[1 2 3]
<class ‘numpy.ndarray’>
(3,)
(1, 3)

2、改变数组中的元素:

c = np.array([1, 2, 3, 4, 5, 6])
c = c.reshape((-1, 2))
print(c.shape)
print(c)
print(c[2, 0])

c[2, 0] = 55
print(c)

结果为:

(3, 2)
[[1 2]
[3 4]
[5 6]]
5
[[ 1 2]
[ 3 4]
[55 6]]

4、zeros 创建全部为0的数组

d = np.zeros((3, 3))
print(d)

结果为:

[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]

5、ones 创建全部为1的数组

e = np.ones((2, 3))
print(e)

结果为:

[[1. 1. 1.]
[1. 1. 1.]]

6、full可代替zeros和ones的功能:

a = np.full((3, 3), 0)
print(a)

a = np.full((2, 3), 1)
print(a)

结果为:

[[0 0 0]
[0 0 0]
[0 0 0]]

[[1 1 1]
[1 1 1]]

7、eye 单位矩阵

f = np.eye(3)
print(f)

结果为:

[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]

8、 生成(0-1)的随机数矩阵

   g = np.random.random((3, 4))
    print(g)

结果为:

[[0.00242217 0.73087671 0.19172274 0.53419157]
 [0.86524713 0.01398055 0.5349048  0.65108886]
 [0.39684444 0.38109035 0.89926698 0.1114804 ]]

题目描述:

对于一维数组或者列表,unique函数去除其中重复的元素,并按元素由大到小返回一个新的无元素重复的元组或者列表.

import numpy as np
A = [1, 2, 2, 5, 3, 4, 3]
print(np.unique(A))
B = (1, 2, 2, 5, 3, 4, 3)
print(np.unique(B))

结果为:

[1 2 3 4 5]
[1 2 3 4 5]

学习链接:https://www.imooc.com/video/16508/0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值