numpy数组的基本操作

数组的基本操作

1.数组的索引、切片

  • 一维、二维、三维的数组切片
    • 直接进行索引,切片
    • 对象[:,:]—先行后列
#对于二维数组
x1 = np.random.uniform(0,1,[4,5]) #生成一个4行5列的波动区间在4~5之间的数组

a = x1[0,0:3]#获取第一行,前3列的数据


#对于三维数组
a1 = np.array([[[1,2,3],[4,5,6]],[[12,14,14],[17,18,19]]])
print(a1)
re = a1[0,0,1:3]#第1个二维数组,第1行,的1、2数
print(re)

2.形状修改

  • ndarry.reshape(shape,order)
    • 返回一个具有相同数据域,但shape不同的视图
    • 行、列不进行互换
#在转换形状的时候,一定要注意数组的元素匹配
stock = np.random.uniform(0,1,[4,5]) #生成一个4行5列的波动区间在4~5之间的数组
stock_change1 = stock.reshape([5,4])#形状由4行5列修改为5行4列
stock_change2 = stock.reshape([-1,10])#数组的形状被修改为(2,10),-1:表示通过待计算
print(stock_change2)

  • ndarray.resize(new_shape)
    • 修改数组本身的形状(需要保持元素个数前后相同)
    • 行、列不进行互换
stock = np.random.uniform(0,1,[4,5]) #生成一个4行5列的波动区间在4~5之间的数组

stock_change2 = stock.resize([2,10])#stock被修改为2行10列
  • ndarray.T
    • 数组的转置
    • 将数组的行、列进行互换
stock_change.T.shape

3.类型修改

  • ndarry.astype(np.int32)
    • 返回修改了类型之后的数组
stock = np.random.uniform(-1,2,[4,5]) #生成一个4行5列的波动区间在4~5之间的数组
a = stock.astype(np.int64)#将stock转换为np.int64类型
print(a)

  • ndarray.tostring([order])或者ndarray.tobytes([order])
    • 构建包含数组中原始数据字节的python字节
a1.tostring()#将数据类型转化为字符串

4.数组的去重

temp = np.array([[1,2,3,4],[3,4,5,6]])
a = np.unique(temp)
print(a)
#数据去重之后全放到一个列表中
posted @ 2023-02-21 19:51  小杨的冥想课  阅读(31)  评论(0编辑  收藏  举报