Numpy学习笔记
一、数据的维度
1 创建数据
创建二维数据
import numpy as np
cars = np.array([5, 10, 12, 6])
print("数据:", cars, "\n维度:", cars.ndim)
创建更高维数据
cars = np.array([
[
[5, 10, 12, 6],
[5.1, 8.2, 11, 6.3],
[4.4, 9.1, 10, 6.6]
],
[
[6, 11, 13, 7],
[6.1, 9.2, 12, 7.3],
[5.4, 10.1, 11, 7.6]
],
])
print("总维度:", cars.ndim)
print("场地 1 数据:\n", cars[0], "\n场地 1 维度:", cars[0].ndim)
print("场地 2 数据:\n", cars[1], "\n场地 2 维度:", cars[1].ndim)
2 添加数据
cars1 = np.array([5, 10, 12, 6])
cars2 = np.array([5.2, 4.2])
cars = np.concatenate([cars1, cars2])
print(cars)
test1 = np.array([5, 10, 12, 6])
test2 = np.array([5.1, 8.2, 11, 6.3])
# 首先需要把它们都变成二维,下面这两种方法都可以加维度
test1 = np.expand_dims(test1, 0)
test2 = test2[np.newaxis, :]
print("test1加维度后 ", test1)
print("test2加维度后 ", test2)
# 然后再在第一个维度上叠加
all_tests = np.concatenate([test1, test2])
print("括展后\n", all_tests)
3 合并数据
print("第一维度叠加:\n", np.concatenate([all_tests, all_tests], axis=0))
print("第二维度叠加:\n", np.concatenate([all_tests, all_tests], axis=1))
a = np.array([
[1,2],
[3,4]
])
b = np.array([
[5,6],
[7,8]
])
print("竖直合并\n", np.vstack([a, b]))
print("水平合并\n", np.hstack([a, b]))
4 观察形态
cars = np.array([
[5, 10, 12, 6],
[5.1, 8.2, 11, 6.3],
[4.4, 9.1, 10, 6.6]
])
count = 0
for i in range(len(cars)):
for j in range(len(cars[i])):
count += 1
print("总共多少测试数据:", count)
print("总共多少测试数据:", cars.size)
print("第一个维度:", cars.shape[0])
print("第二个维度:", cars.shape[1])
print("所有维度:", cars.shape)
二、数据的选择
1 单个选取
a = np.array([1, 2, 3])
print("a[0]:", a[0])
print("a[1]:", a[1])
print("a[[0,1]]:", a[[0,1]])
print("a[[1,1,0]]:", a[[1,1,0]])
二维或者多维数据也可以用上面的方法来选择数据
b = np.array([
[1,2,3,4],
[5,6,7,8],
[9,10,11,12]
])
# 选第 2 行所有数
print("b[1]:", b[1])
# 选第 2 行,第 1 列的数
print("b[1,0]:", b[1,0])
# 这个看着有点纠结,如果对应到数据,
# 第一个拿的是数据位是 [1,2]
# 第二个拿的是 [0,3]
print("b[[1,0],[2,3]]:",
b[[1,0],
[2,3]])
2 切片划分
a = np.array([1, 2, 3])
print("a[0:2]:", a[0:2])
print("a[1:]:", a[1:])
print("a[-2:]:", a[-2:])
多维切片
b = np.array([
[1,2,3,4],
[5,6,7,8],
[9,10,11,12]
])
print("b[:2]:\n", b[:2])
print("b[:2, :3]:\n", b[:2, :3])
print("b[1:3, -2:]:\n", b[1:3, -2:])
3 条件筛选
a = np.array([
[1,2,3,4],
[5,6,7,8],
[9,10,11,12]
])
print(a[a>7])
condition = a > 7
print(condition)
print(a[condition])
condition = a > 7
print(np.where(condition, -1, a))
condition = a > 7
print(np.where(condition, -1, 2))
condition = a > 7
b = -a - 1
print(np.where(condition, a, b))
三、基础运算
1 加减乘除
import numpy as np
a = np.array([150, 166, 183, 170])
print(a + 3)
print("a + 3:", a + 3)
print("a - 3:", a - 3)
print("a * 3:", a * 3)
print("a / 3:", a / 3)
a = np.array([
[1, 2],
[3, 4]
])
b = np.array([
[5, 6],
[7, 8]
])
print(a.dot(b))
print(np.dot(a, b))
矩阵还有很多其他的计算,比如 np.outer()
矩阵外积,np.inner()
矩阵内积 (和 np.dot()
的用法稍稍有些不同,你可以理解成 np.dot(a, b)= np.inner(a, b.T)
, 把 b 做一次转置)。
2 数据统计分析
a = np.array([150, 166, 183, 170])
print("最大:", np.max(a))
print("最小:", a.min())
print(a.sum())
a = np.array([150, 166, 183, 170])
print("累乘:", a.prod())
print("总数:", a.size)
a = np.array([0, 1, 2, 3])
print("非零总数:", np.count_nonzero(a))
month_salary = [1.2, 20, 0.5, 0.3, 2.1]
print("平均工资:", np.mean(month_salary))
print("工资中位数:", np.median(month_salary))
month_salary = [1.2, 20, 0.5, 0.3, 2.1]
print("标准差:", np.std(month_salary))
3 特殊运算符号
找到最大最小值的索引
a = np.array([150, 166, 183, 170])
name = ["小米", "OPPO", "Huawei", "诺基亚"]
high_idx = np.argmax(a)
low_idx = np.argmin(a)
print("{} 最高".format(name[high_idx]))
print("{} 最矮".format(name[low_idx]))
a = np.array([150.1, 166.4, 183.7, 170.8])
print("ceil:", np.ceil(a))
print("floor:", np.floor(a))
np.clip()
来做上下界限的值截取。
a = np.array([150.1, 166.4, 183.7, 170.8])
print("clip:", a.clip(160, 180))
四、改变数据形态
1 改变形态
a = np.array([1,2,3,4,5,6])
a_2d = a[np.newaxis, :]
print(a.shape, a_2d.shape)
print(a_2d)
a = np.array([1,2,3,4,5,6])
a_none = a[:, None]
a_expand = np.expand_dims(a, axis=1)
print(a_none.shape, a_expand.shape)
a_squeeze = np.squeeze(a_expand)
a_squeeze_axis = a_expand.squeeze(axis=1)
print(a_squeeze.shape)
print(a_squeeze_axis.shape)
上述方法都是添加维度的方式,但是,在机器学习中,我们还有一个更常见的操作,是要改变 shape。维度的添加减少,只能添加减少一个维度,数据结构是不变的。 但是 np.reshape()
可以改变数据结构。 举个例子,a[None, :]
之后,a.shape
会在第一个维度上多一个 1,而 a.reshape([2,3])
则可以更加自定义的将维度内的个数进行修改。 从而达到改变维度及尺寸
a = np.array([1,2,3,4,5,6])
a1 = a.reshape([2, 3])
a2 = a.reshape([3,1,2])
print("a1 shape:", a1.shape)
print(a1)
print("a2 shape:", a2.shape)
print(a2)
其实还有更过的改变形态的方法,比如让数据变直、展平 的 np.ravel()
, np.flatten()
a = np.array([1,2,3,4,5,6]).reshape([2, 3])
aT1 = a.T
aT2 = np.transpose(a)
print(aT1)
print(aT2)
2 合并
一般来说,在数据分析统计,机器学习中的数据,都是以二维来存储的。行是数据样本(第一维度),列是特征(第二维度)。 所以我们可以组合特征和组合样本。 比如将列column
合并,特征 a 的数据和特征 b 的数据合并。
feature_a = np.array([1,2,3,4,5,6])
feature_b = np.array([11,22,33,44,55,66])
c_stack = np.column_stack([feature_a, feature_b])
print(c_stack)
sample_a = np.array([0, 1.1])
sample_b = np.array([1, 2.2])
c_stack = np.row_stack([sample_a, sample_b])
print(c_stack)
上面的两种方法 np.column_stack()
和 np.row_stack()
和后面的 np.vstack()
、np.hstack()
相比, 有些特殊之处,我们先看看使用 vstack
和 hstack
的案例,再说说不同处吧。
feature_a = np.array([1,2,3,4,5,6])[:, None]
feature_b = np.array([11,22,33,44,55,66])[:, None]
c_stack = np.hstack([feature_a, feature_b])
print(c_stack)
sample_a = np.array([0, 1.1])[None, :]
sample_b = np.array([1, 2.2])[None, :]
c_stack = np.vstack([sample_a, sample_b])
print(c_stack)
用 column_stack
和 row_stack()
的时候,Numpy 自动帮你处理的维度信息,而用 vstack
和 hstack
的时候,你需要先确保维度信息是正确的,然后再合并。
有时候,你想要用统一的方法来处理各种不同情况的合并,np.concatenate()
是我最喜欢的方法,管它什么 vstack
hstack
甚至是在更高维度上要合并, 我们都可以用 concatenate()
一个功能实现。
a = np.array([
[1,2],
[3,4]
])
b = np.array([
[5,6],
[7,8]
])
print(np.concatenate([a, b], axis=0))
print(np.concatenate([a, b], axis=1))
3 拆解
同样,能横着,竖着合并,那也能横着竖着拆解。np.vsplit()
和 np.hsplit()
就是干这事的。 如果直接在 indices_or_sections
后填入数字,就是要整分的段数, 而如果接着的是一个列表,那就按照列表中的 index 来取区间。可以看看下面代码注解中的意思
a = np.array(
[[ 1, 11, 2, 22],
[ 3, 33, 4, 44],
[ 5, 55, 6, 66],
[ 7, 77, 8, 88]]
)
print(np.vsplit(a, indices_or_sections=2)) # 分成两段
print(np.vsplit(a, indices_or_sections=[2,3])) # 0~2 一段,2~3 一段,3~一段 可理解为以2和3为为分界点进行四段划分
np.vsplit
是拿着刀沿着横向切分,那么 np.hsplit
就是沿纵向切分
a = np.array(
[[ 1, 11, 2, 22],
[ 3, 33, 4, 44],
[ 5, 55, 6, 66],
[ 7, 77, 8, 88]]
)
print(np.split(a, indices_or_sections=2, axis=0)) # 分成两段
print(np.split(a, indices_or_sections=[2,3], axis=1)) # 在第二维度, 0~2 一段,2~3 一段,3~一段
print(np.vsplit(a, indices_or_sections=2)) # 分成两段
print(np.vsplit(a, indices_or_sections=[2,3])) # 0~2 一段,2~3 一段,3~一段 可理解为以2和3为为分界点进行四段划分