20190222_一堆数据摆在你面前,老板让你画成图表,怎么做?

Jupyter Notebook
20190222_一堆数据摆在你面前,老板让你画成图表,怎么做?

http://mp.weixin.qq.com/s?__biz=MzU4NjUxMDk5Mg==&mid=2247485175&idx=1&sn=9c8894eb592187a59e10d9dff54d183d&chksm=fdfb6108ca8ce81e95401419bf09900f201d17def6daa8062d69fb3ad64d7403f85eacb5021e&mpshare=1&scene=1&srcid=0222szrqItFh75FwYXCw1PjX#rd

小技巧

避免采用隐式拷贝,多用就地操作,比如你想打印5个b,有两种方法:

# 方法1:
b = 5
b *= 5
print(b)
# 方法2:
b = 5
a = b * 5
print(a)
25
25

ndarray 对象

创建数组

import numpy as np

a = np.array([[1,2,3],[4,5,6],[7,8,9]])
print (a)
[[1 2 3]
 [4 5 6]
 [7 8 9]]

用shape 属性获得数组的大小

import numpy as np
a = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(a.shape)
(3, 3)

更改数组的元素,把元素中5 换成0,直接用小标

a = np.array([[1,2,3],[4,5,6],[7,8,9]])
a[1,1] = 0
print (a)
[[1 2 3]
 [4 0 6]
 [7 8 9]]

通过dtype获得元素的属性

import numpy as np
​
a = np.array([[1,2,3],[4,5,6],[7,8,9]])
print (a.dtype)
int32

结构数组

自定义结构数组

import numpy as np
​
student_type = np.dtype({
    'names':['name','chinese','math','english'],
    'formats': ['S32', 'i', 'i', 'i']
})

定义真实数组

students = np.array([('zhangsan',85,72,56),('lisi',88,90,68),
                     ('wangwu',78,66,88)],dtype = student_type)

取出全部值

name = students[:]['name']
print(name)
chinese = students[:]['chinese']
print(chinese)
math = students[:]['math']
print(math)
english = students[:]['english']
[b'zhangsan' b'lisi' b'wangwu']
[85 88 78]
[72 90 66]

求平均值

print(np.mean(chinese))
print(np.mean(math))
print(np.mean(english))
83.66666666666667
76.0
70.66666666666667

ufun 运算

创建连续数组

# 方法一:arange(初始值,终值,步长) # 终值为开区间
import numpy as np
​
b = np.arange(1,8,2)
print(b)
[1 3 5 7]
# 方法二:linspace(初始值,终值,元素个数),其中终值是闭区间import numpy as np
​
b = np.linspace(1,7,4)
print(b)
[1. 3. 5. 7.]

算法运算

加减乘除

import numpy as np
​
b = np.linspace(1,7,4)
c = np.arange(1,8,2)print(np.add(b,c))       # 加法运算
print(np.subtract(b,c))  # 减法运算
print(np.multiply(b,c))  # 乘法运算
print(np.divide(b,c))    # 除法运算
print(np.mod(b,c))       # 取余运算
[ 2.  6. 10. 14.]
[0. 0. 0. 0.]
[ 1.  9. 25. 49.]
[1. 1. 1. 1.]
[0. 0. 0. 0.]

最大值,最小值,平均值,标准差,方差


a = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(a.max())   # 数组中最大值
print(a.min())   # 数组中最小值
print(a.mean())  #数组中的平均值
print(a.std())   # 数组中的标准差
print(a.var())   # 数组中的方差
9
1
5.0
2.581988897471611
6.666666666666667

猜你喜欢

转载自blog.csdn.net/u012914436/article/details/87872087
今日推荐