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

背景介绍/一些废话

为准备上海市计算机等级考试三级——数据科学(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
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值