1、numpy数组与列表的区别
Python列表可以存储一维数组,通过列表的嵌套可以实现多维数组的处理。
Numpy是一个第三方库,可以使用库中的ndarray对象来处理多维数组,该对象是一个快速而灵活的大数据容器。
既然python中含有可以处理一维数组和多维数组的能力,为何还要用第三方库numpy呢?
因为Numpy是专门针对数组的操作和运算而进行设计的,所以数组的存储效率和输入输出性能远优于Python中的嵌套列表,数组越大,数据量越大,Numpy的优势就越明显。
注:通常Numpy数组中的所有元素的类型都是相同的,而Python列表中的元素类型是任意的。
从通用性能上来看:Numpy数组不及Python列表;
但在科学计算中,可以省掉很多循环语句,Numpy数组比Python列表快得多。
代码中常见的情况:
1.1、进行转置处理
#数组可以进行转置
import numpy as np
a = np.array([[1, 2, 0, 1], [1, 6, 9, 55], [7, 8, 9, 5]]) # a为数组
print(a.T)
#列表不可以进行转置
a = [[1, 2, 0, 1], [1, 6, 9, 55], [7, 8, 9, 5]] # a为列表
print(a.T)
#输出结果显示:
"""
[[ 1 1 7]
[ 2 6 8]
[ 0 9 9]
[ 1 55 5]]
AttributeError: 'list' object has no attribute 'T'
"""
1.2、进行.shape输出
#数组可以使用.shape
import numpy as np
a = np.array([[1, 2, 3], [1, 1, 4], [1, 5, 1]])
print(a.shape)
#列表不能使用.shape
a = [[1, 2, 3], [1, 1, 4], [1, 5, 1]]
print(a.shape)
#输出结果:
"""
(3, 3)
AttributeError: 'list' object has no attribute 'shape'
"""
1.3、数组和列表关于乘号*的应用
from numpy import *
# a为数组
a = array([[1, 2, 3],
[4, 5, 6]])
b = 4 * a
print(b)
# c为列表
c = ([[1, 2, 3],
[4, 5, 6]])
d = 4 * c
print(d)
结果显示:
[[ 4 8 12]
[16 20 24]]
[[1, 2, 3], [4, 5, 6], [1, 2, 3], [4, 5, 6], [1, 2, 3], [4, 5, 6], [1, 2, 3], [4, 5, 6]]
2、numpy数组其它常见应用
2.2、改变原始数组结构
比如将四行三列的数组改为十二行一列和三行四列,操作代码如下:
import numpy as np
a=np.array([[1,2,3],[1,1,4],[1,5,1],[1,1,4]])
a=a.reshape(-1,1)
print(a)
print("\n")
# 每四个数字为一行
b=a.reshape(-1,4)
print(b)
结果输出为:
[[1]
[2]
[3]
[1]
[1]
[4]
[1]
[5]
[1]
[1]
[1]
[4]]
[[1 2 3 1]
[1 4 1 5]
[1 1 1 4]]
参考
http://blog.sina.com.cn/s/blog_d8f6ec6b0102wtbh.html
https://blog.csdn.net/qq_35752161/article/details/83004587