Task:03 numpy中数组的操作(学习笔记)

数组的操作

xxx.shape()

可以通过xxx.shape()来改变数组的维数

import numpy as np
x = np.array([1, 2, 9, 4, 5, 6, 7, 8])
x.shape = [2, 4]
print(x)
# [[1 2 9 4]
#  [5 6 7 8]]

xxx.flat

可以将数组转换为一维

import numpy as np
x = np.array([[11, 12, 13, 14, 15],
              [16, 17, 18, 19, 20],
              [21, 22, 23, 24, 25],
              [26, 27, 28, 29, 30],
              [31, 32, 33, 34, 35]])
y = x.flat
for i in y:
    print(i, end=' ')
# 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
y[3] = 0
print(end='\n')
print(x)
# [[11 12 13  0 15]
#  [16 17 18 19 20]
#  [21 22 23 24 25]
#  [26 27 28 29 30]
#  [31 32 33 34 35]]

xxx.flatten()

这个函数的作用就是拷贝复制的作用,可以对比一下上一个例子中xxx.flat两个不同的区别。在于后面的索引的时候,这个函数并不会改变,而上一个函数同样的操作却会改变。

import numpy as np
x = np.array([[11, 12, 13, 14, 15],
              [16, 17, 18, 19, 20],
              [21, 22, 23, 24, 25],
              [26, 27, 28, 29, 30],
              [31, 32, 33, 34, 35]])
y = x.flatten()
print(y)
# [11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
#  35]
y[3] = 0
print(x)
# [[11 12 13 14 15]
#  [16 17 18 19 20]
#  [21 22 23 24 25]
#  [26 27 28 29 30]
#  [31 32 33 34 35]]

数组转置

线性代数中有一个知识点就是矩阵的转置,那在numpy中也是可以实现转置功能的。
语法:

np.transpose()
import numpy as np
a = np.arange(2, 14).reshape((3,4))
print(a)
'''
[[ 2  3  4  5]
 [ 6  7  8  9]
 [10 11 12 13]]
 '''
 print(np.transpose(a))
 '''
 [[ 2  6 10]
 [ 3  7 11]
 [ 4  8 12]
 [ 5  9 13]]
 '''

数组拼接

将两个数组进行拼接可以使用下面的方法

np.concatenate([x, y])
import numpy as np
x = np.array([1, 2, 3])
y = np.array([7, 8, 9])
z = np.concatenate([x, y])
print(z)
# [1 2 3 7 8 9]
z = np.concatenate([x, y], axis=0)
print(z)
# [1 2 3 7 8 9]

如果是一维的数组加后也是一维的数组
原来是二维的数组拼接后也是二维的数组

import numpy as np
x = np.array([1, 2, 3]).reshape(1, 3)
y = np.array([7, 8, 9]).reshape(1, 3)
z = np.concatenate([x, y])
print(z)
'''
[[ 1  2  3]
 [ 7  8  9]]
'''
z = np.concatenate([x, y], axis=0)
print(z)
'''
[[ 1  2  3]
 [ 7  8  9]]
'''

数组拆分

import numpy as np
x = np.array([[11, 12, 13, 14],
              [16, 17, 18, 19],
              [21, 22, 23, 24]])
y = np.split(x, [1, 3])
print(y)
'''
 [array([[11, 12, 13, 14]]), array([[16, 17, 18, 19],
        [21, 22, 23, 24]]), array([], shape=(0, 4), dtype=int32)]
'''
y = np.split(x, [1, 3], axis=1)
print(y)
'''
 [array([[11],
        [16],
        [21]]), array([[12, 13],
        [17, 18],
        [22, 23]]), array([[14],
        [19],
        [24]])]
'''
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值