Numpy笔记1

##numpy笔记1

import numpy as np

a = np.array([[1, 2], [3, 4]])
print(a)

#输出
#[[1, 2]
#[3, 4]]

dt = np.dtype([(‘age’,np.int8)])
a = np.array([(10,),(20,),(30,)], dtype = dt)
print(a[‘age’])

#输出
#[10 20 30]

student = np.dtype([(‘name’,‘S20’), (‘age’, ‘i1’), (‘marks’, ‘f4’)])
a = np.array([(‘abc’, 21, 50),(‘xyz’, 18, 75)], dtype = student)
print(a)

#输出
#[(‘abc’, 21, 50.0), (‘xyz’, 18, 75.0)]

#每个内建类型都有一个唯一定义它的字符代码:
‘b’:布尔值
‘i’:符号整数
‘u’:无符号整数
‘f’:浮点
‘c’:复数浮点
‘m’:时间间隔
‘M’:日期时间
‘O’:Python 对象
‘S’, ‘a’:字节串
‘U’:Unicode
‘V’:原始数据(void)

#数组大小
a = np.array([[1,2,3],[4,5,6]])
print(a.shape)

#输出
#(2, 3)

#调整数组大小
b = a.reshape(3,2)
print(b)

#输出
#[[1, 2]
[3, 4]
[5, 6]]

#等间距数组
a = np.arange(24)
print(a)

#输出
#[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]

#返回数组中每个元素的字节单位长度
x = np.array([1,2,3,4,5], dtype = np.int8)
print(x.itemsize)

#输出
#1

#创建空数组
x = np.empty([3,2], dtype = int)
print(x)

#输出
#[[22649312 1701344351]
[1818321759 1885959276]
[16779776 156368896]]
#未初始化的数组元素为随机值

#创建以0填充的新数组
x = np.zeros((2,5))
print(x)

#输出
#[[0 0 0 0 0]
[0 0 0 0 0]]

#创建以1填充的新数组,dtype可选,默认为float
x = np.ones([2,2], dtype = int)
print(x)

#输出
#[[1 1]
[1 1]]

#将 Python 序列转换为ndarray
numpy.asarray(a, dtype = None, order = None)
#a 任意形式的输入参数,比如列表、列表的元组、元组、元组的元组、元组的列表
#dtype 通常,输入数据的类型会应用到返回的ndarray

x = [1,2,3]
a = np.asarray(x, dtype = float)
print(a)

#输出
#[ 1. 2. 3.]

x = (1,2,3)
a = np.asarray(x)
print(a)

#输出
#[1 2 3]

#将缓冲区解释为一维数组。 暴露缓冲区接口的任何对象都用作参数来返回ndarray
s = ‘Hello World’
a = np.frombuffer(s, dtype = ‘S1’)
print(a)

#输出
#[‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ’ ’ ‘W’ ‘o’ ‘r’ ‘l’ ‘d’]

#从任何可迭代对象构建一个ndarray对象,返回一个新的一维数组。
list = range(5)
it = iter(list)
使用迭代器创建 ndarray
x = np.fromiter(it, dtype = float)
print(x)

#输出
#[0. 1. 2. 3. 4.]

#返回ndarray对象,包含给定范围内的等间隔值。
numpy.arange(start, stop, step, dtype)
#start 起始值
#stop 终止值(不包含)
#step 步长

x = np.arange(10,20,2)
print(x)

#输出
#[10 12 14 16 18]

#类似于arange()函数。 在此函数中,指定了范围之间的均匀间隔数量,而不是步长。
numpy.linspace(start, stop, num, endpoint, retstep, dtype)
#start 序列的起始值
#stop 序列的终止值,如果endpoint为true,该值包含于序列中
#num 要生成的等间隔样例数量,默认为50
#endpoint 序列中是否包含stop值,默认为ture
#retstep 如果为true,返回样例,以及连续数字之间的步长
#dtype 输出ndarray的数据类型

x = np.linspace(10,20,5)
print(x)

#输出
#[10. 12.5 15. 17.5 20.]

#此函数返回一个ndarray对象,其中包含在对数刻度上均匀分布的数字。 刻度的开始和结束端点是某个底数的幂,通常为 10。
numpy.logscale(start, stop, num, endpoint, base, dtype)

a = np.logspace(1,10,num = 10, base = 2)
print(a)

#输出
#[ 2. 4. 8. 16. 32. 64. 128. 256. 512. 1024.]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值