【Python 基础】Numpy 模块

本文详细介绍了NumPy库中数组的创建方法,包括使用array、zeros、ones等函数,以及如何通过指定数据类型、维度和顺序来定制数组。同时,文章探讨了广播、布尔索引等高级操作,为读者提供了深入理解NumPy数组处理的全面指南。

user_docs

array

import numpy as np
array(object,dtype=None,copy=True,order='K',subok=False,ndmin=0)
# obj: data
# dtype: data type
# order: list
# ndmin: dimintion
nd = np.array((1,2,3,4))
nd.dtype
nd.ndim
np.array(([1,2,3,][1,2]))  # dtype is object, not int32

  • order C
    np.array([range(1,4),range(4,8)],order=‘C’)
1234
5678
  • order F
    np.array([range(1,4),range(4,8)],order=‘F’)
15
26
37
48

ndarray

# create 2 x 2 array
np.ndarray((2,2), buffer=np.array(range(4)), dtype=int)
.shape
.size
.dtype
.data
.reshape(m,n)

# slice
a[:]
b[[0,1]]
b[::, 1]
b[[1,2],[1,2]]?
b[::,[1,4],b[::,::2]]

create ndarray ways

np.zeros()
np.zeros_like/ones_likes/empty_like(a, ...)
full(shape,  fill, dtype, order)
arange(start, stop, step, stype)
linspace(start, stop, num=50)
random.rand/randn(d0, d1...)
random.randint(low, high, size)

# dtype: bool, float, int
# character code ('biufcmMOSUV') 
np.typeDict
np.typecodes
np.typeNA

create data type

1. date: name, age, eg.[(‘sun’, 10), (‘yang’, 11)]

dt = np.dtype('U16','i4')
a = np.array([('sun', 10), ('yang', 11)], dtype=dt)
a['f0']  # silce
a['f1']  
dt = np.dtype('3S8', '')

2. second way

dt = np.dtype([('name', 'U16'),('age', 'i4')])

3. third way

dt = np.dtype(['f0',[('f1','U2'),('f2', np.int16)]])
dt = np.dtype([('name', 'U16'),('age', 'i4')])

dt = np.dtype({'x': ('S2', 0), 'y': ('i4', 2)})
dt = np.dtype({'name': ['name', 'age'], 'formats': ['U16', 'i4']})

calculate

# broadcasting: + - * /

# boolean index
np.any
np.all
np.where(cond,[x,y])

&  # 逻辑与
|  # 逻辑或

np.all
np.arange(9).reshape(3,3)
# return an array representing the indices of a grid
np.indices(a.shape)
r, c = np.indices(a.shape)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值