L1 = [True, "2", 3.0, 4]
types = [type(i) for i in L1]
types
结果:
[bool, str, float, int]
注意:每个元素类型不一样,给数据的存储和获取增加负担。
在实现层面,数组本质上包含一个指向一个连续数据块的指针。而Python列表包含一个指向指针块的指针,每个指针又指向一个完整的Python对象。如下图所示:
(请pip install datascience)
from datascience import *
baseline_high = 14.48
highs = make_array(baseline_high - 0.880, baseline_high - 0.093,
baseline_high + 0.105, baseline_high + 0.684)
highs
type(highs)
结果:
array([13.6 , 14.387, 14.585, 15.164])
numpy.ndarray
import numpy as np
# Creating Arrays from Python Lists
a = np.array([4, 2.0, 8,6])
type(a)
a.dtype
结果:
numpy.ndarray
dtype('float64')
注:以下都是在 import numpy as np的条件下执行
1.标量
np.array(12)
2.矢量
a = np.arange(12)
a
结果:
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
3.矩阵
#3行2列矩阵
b = np.array([[1,2],
[4,5],
[7,8]])
4.三维数组
c = np.arange(1,19).reshape(3,2,3)
c
结果:
array([[[ 1, 2, 3],
[ 4, 5, 6]],
[[ 7, 8, 9],
[10, 11, 12]],
[[13, 14, 15],
[16, 17, 18]]])
5.所有元素为0的数组
np.zeros(10,dtype=int)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
6.所有元素为1的数组
np.ones((3,5),dtype=float)
array([[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.]])
7.所有元素相同的数组
np.full((6, 5), 3.14)
array([[3.14, 3.14, 3.14, 3.14, 3.14],
[3.14, 3.14, 3.14, 3.14, 3.14],
[3.14, 3.14, 3.14, 3.14, 3.14],
[3.14, 3.14, 3.14, 3.14, 3.14],
[3.14, 3.14, 3.14, 3.14, 3.14],
[3.14, 3.14, 3.14, 3.14, 3.14]])
8.对角矩阵
np.eye(3)
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
# read numpy from csv file
titanic = "titanic.csv"
titanic_data = np.loadtxt(titanic,delimiter=",",skiprows= 1,usecols=(0,1,3,4,7),dtype=str)
titanic_data.dtype
结果:
dtype(')#长度为8位的unicode类型数据
查看几行几列
titanic_data.shape
结果:
(887, 5)
查看有多少元素
titanic_data.size
结果:
4435
查看是几维数组
titanic_data.ndim
结果:
2
矩阵转置
np.ones((3,5),dtype=float).T
结果:
array([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
a = np.arange(18).reshape(3,6)
print(a)
[[ 0 1 2 3 4 5]
[ 6 7 8 9 10 11]
[12 13 14 15 16 17]]
1.第一行
print(a[0])
[0 1 2 3 4 5]
2.前两行
print(a[0:2])
[[ 0 1 2 3 4 5]
[ 6 7 8 9 10 11]]
3.所有行
print(a[:])
[[ 0 1 2 3 4 5]
[ 6 7 8 9 10 11]
[12 13 14 15 16 17]]
4.第一列
print(a[:,0])
[ 0 6 12]
5.前两列
print(a[:,:2])
print(a[:,[0,1])
[[ 0 1]
[ 6 7]
[12 13]]
6.位于第一行第一列的元素
print(a[0][0])
0
切片元素发生改变原来的数组也发生改变
a = np.arange(6).reshape(2,3)
a
array([[0, 1, 2],
[3, 4, 5]])
b = a[0:2,0:2]
print(b)
b[0,0] = 1
print(b)
print(a)
[[0 1]
[3 4]]
[[1 1]
[3 4]]
[[1 1 2]
[3 4 5]]
L2 = [1,2,3,4]
Ls = L2[0:2]
print(L2)
print(Ls)
Ls[0] = 100
print(Ls)
print(L2)
[1, 2, 3, 4]
[1, 2]
[100, 2]
[1, 2, 3, 4]