读书笔记【数据科学】ch02多维数据结构与运算

it2022-05-05  164

目录

背景介绍/一些废话知识点二维切片条件筛选聚集函数

背景介绍/一些废话

为准备上海市计算机等级考试三级——数据科学(Anaconda3环境),所以打算把推荐书目《数据科学技术与应用》(宋晖、刘晓强 主编)刷一遍,当作查缺补漏。 以下记录一些之前没搞清的细节。

知识点

二维切片

牢记

arr [ row, column ][a:b] b不取横竖都有的混合切需要两层切片

这样后面才不会搞混! 用例子记住好了。

import numpy as np s = np.array([[0,1,2,3],[4,5,6,7],[8,9,10,11]]) # 先创立个二维数组 >>> s[[0,2],1:4] array([[ 1, 2, 3], [ 9, 10, 11]]) >>> s[[0,2]][:,[1,4]] Traceback (most recent call last): File "<pyshell#23>", line 1, in <module> s[[0,2]][:,[1,4]] IndexError: index 4 is out of bounds for axis 1 with size 4 >>> s[[0,2]][:,[1,2,3]] array([[ 1, 2, 3], [ 9, 10, 11]]) >>> s[[0,2]][:,[1,3]] array([[ 1, 3], [ 9, 11]]) >>> s[[0,2],[1,3]] #返回坐标为(0,1),(2,3)的元素 array([ 1, 11])

条件筛选

test[(test == 's4')|(test == '……')] 其中,(test == 's4')|(test == '……')返回的是array([False,False,False,False,True,False,True],dtype = bool) 最终返回array([‘s4’,'……'],dtype = '<U3') 一维看起来很无聊,但给二维打下基础。

还是用这个例子,增加属性名。

import numpy as np s = np.array([[0,1,2,3],[4,5,6,7],[8,9,10,11]]) # 先创立个二维数组 a = numpy.array(['a','b','c','d']) #增加每列属性名 b = numpy.array(['x','y','z']) #增加每行属性名 >>> s[(b == 'x')|(b == 'z')] array([[ 0, 1, 2, 3], [ 8, 9, 10, 11]]) >>> s[b > 'x'] array([[ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> s[:,a == 'b'] array([[1], [5], [9]]) >>> s[:,a >= 'b'] array([[ 1, 2, 3], [ 5, 6, 7], [ 9, 10, 11]])

聚集函数

容易忘掉使用axis参数 axis=0:对列进行操作 axis=1:对行进行操作 还是用上面的例子s

求平均数: >>> s.mean(axis=1) array([1.5, 5.5, 9.5]) >>> s.mean(axis=0) array([4., 5., 6., 7.]) 求和: >>> s.sum(axis=0) array([12, 15, 18, 21]) 累加: >>> s.cumsum(axis=0) array([[ 0, 1, 2, 3], [ 4, 6, 8, 10], [12, 15, 18, 21]], dtype=int32) >>> s.cumsum(axis=1) array([[ 0, 1, 3, 6], [ 4, 9, 15, 22], [ 8, 17, 27, 38]], dtype=int32) 累乘: >>> s.cumprod(axis=1) array([[ 0, 0, 0, 0], [ 4, 20, 120, 840], [ 8, 72, 720, 7920]], dtype=int32) >>> s.cumprod(axis=0) array([[ 0, 1, 2, 3], [ 0, 5, 12, 21], [ 0, 45, 120, 231]], dtype=int32)

然后混合使用条件筛选就可以办到很多事(令人想起了关系代数)。 比如选出英语成绩最高同学 names[scores[:subjects=='English'].ardmax()]


最新回复(0)