Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Data Analysis with Python——02 #82

Open
hsipeng opened this issue Aug 23, 2019 · 0 comments
Open

Data Analysis with Python——02 #82

hsipeng opened this issue Aug 23, 2019 · 0 comments

Comments

@hsipeng
Copy link
Owner

hsipeng commented Aug 23, 2019

Data Analysis with Python——02

Numpy

numpy 函数
Screen Shot 2019-03-11 at 3.25.13 PM.png

数据类型

Screen Shot 2019-03-11 at 3.29.56 PM.png

数组和标量之间的运算

数组很重要,因为它使你不用编写循环即可对数据执行批量运算。这通常就叫做矢量化(vectorization)。大小相等的数组之间的任何算术运算都会将运算应用到元素级。不同大小的数组之间的运算叫做广播(broadcasting)。

基本的索引和切片

arr = np.arange(10)
arr
# array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
arr[5:8]

# array([5, 6, 7])
arr[5:8] = 12

# array([0, 1, 2, 3, 4, 12, 12, 12, 8, 9])

想要得到一份副本而非视图, 需要显示的复制, 例如: arr[5:8].copy()

多维数组访问

Screen Shot 2019-03-11 at 3.40.08 PM.png

切片是沿着一个轴向选取元素的。你可以一次传入多个切片,就像传入多个索引那样:

In[78]:arr2d[:2,1:]

Out[78]:array([[2,3],[5,6]])

像这样进行切片时,只能得到相同维数的数组视图。通过将整数索引和切片混合,可以得到低维度的切片:

In[79]:arr2d[1,:2]
In[80]:arr2d[2,:1]

Out[79]:array([4,5])
Out[80]:array([7])

Screen Shot 2019-03-11 at 3.44.50 PM.png

布尔类型数组索引

data[names == 'Bob',3]
data[names != 'Bob',3]
data[-(names == 'Bob'),3]
data[age < 20 ,3]
...

Python关键字and和or在布尔型数组中无效。

花式索引

花式索引总是将数据复制到新数组中

数组转置和轴对换

  • transpose
  • T 属性
  • swapaxes
np.dot(arr.T , arr)

通用函数: 快速的元素级数组函数

Screen Shot 2019-03-11 at 3.57.51 PM.png
Screen Shot 2019-03-11 at 3.57.40 PM.png

将条件逻辑表述为数组运算

np.where

数学和统计方法

Sum、mean 以及标准差std 等聚合计算(约简计算), 既可以当作数组的实例方法也可以当作顶级NumPy函数使用

arr = np.random.randn(5,4) # 模拟正态分布的数据

arr.mean()
# 0.062814911084854597
np.mean(arr)
# 0.062814911084854597

Screen Shot 2019-03-11 at 4.07.24 PM.png

用于布尔型数组的方法

  • sum
    经常用来对布尔型数组中的True 值计数
  • any
    是否存在一个或多个True
  • all
    都是True
arr = randn(100)

(arr > 0).sum()
bools = np.array([False, False, True, False])
bools.any()
# True
bools.all()
# False

排序
Sort

唯一化

np.unique
找出数组中的唯一值,并且返回已排序的结果

Screen Shot 2019-03-11 at 4.14.44 PM.png

用于数组的文件输入输出

np.save 和 np.load
np.savez和 np.load
np.savetxt和 np.loadtext

arr = np.arange(10)

np.save('some_array', arr) # 后缀 .npy

np.load('some_array.npy')


np.loadtxt('some_ex.txt', delimiter=',')# 以逗号隔开的文本文件
np.savetxt('some_ex.txt', arr)

线性代数
Screen Shot 2019-03-11 at 4.21.19 PM.png

随机数生成
Screen Shot 2019-03-11 at 4.22.35 PM.png

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant