本地代码是.ipynb格式的转换到博客上很麻烦,这里展示部分代码,了解更多可以查看我的git-hub:https://github.com/Yangami/Python-for-Statisticians/tree/master/Numpy
#-*-author Yangami-*-
import numpy as np
import pandas as pd
shape
#创建数组 a=np.array([1,2,3]) b=np.arange(9) a,b,type(a) c=np.array([[[1,2,3],[2,4,6]],[[1,2,3],[2,4,6]]]) c np.shape(c) np.shape(a) np.array([[[1,2,3],[4,5,6]],[[1,2,3],[4,5,6]]]) #数组转列表 c.tolist()
reshape
a=np.array([[1,2,3,4,5,6]]) a.reshape(6,1) a.reshape(2,3) np.array([60, 31, 54, 78,89,34,65,78,56,77,88,44 ]).reshape(3,4) a.reshape(1,-1)
基本运算
a a+1 a*2 np.log(a) a #条件选择返回bool值 a>2 #bool值做索引 a[a>2] # # 拆分合并 a=a.reshape(2,3) a #取某行 a[1] #取某列 a[1,1:] a[1][2] #取元素 a[1,2],a[1][2] #拆分数组 a1=a[:,:1] a2=a[:,1:] print(a1,' ',a2) #合并数组 a1+a2 hstack((a1,a2)) vstack((a[0],a[1]))
矩阵运算
a=np.arange(4).reshape(2,2) a #对应元素乘 a*a #矩阵乘法 a.dot(a) #转化为矩阵 a=np.matrix(a) print(type(a)) #矩阵乘法 b=a*a b #转置 b.T
广播机制
#考虑维度不相等情况下数组的运算 arr1 = np.array([[0, 0, 0],[1, 1, 1],[2, 2, 2], [3, 3, 3]]) #arr1.shape = (4,3) arr2 = np.array([1, 2, 3]).reshape(1,-1) #arr2.shape = (1,3) arr1,arr2 arr_sum = arr1 + arr2 print(arr_sum)
arr1 = np.array([[0, 0, 0],[1, 1, 1],[2, 2, 2], [3, 3, 3]]) #arr1.shape = (4,3) arr2 = np.array([[1],[2],[3],[4]]) #arr2.shape = (4, 1) print(arr1,arr2)
arr_sum = arr1 + arr2
print(arr_sum)
统计
#按行按列计算 a=np.arange(9).reshape(3,3) a,np.shape(a)
#直接求平均
np.mean(a)
#求每行平均值
np.mean(a,axis=1)
#求每列平均值
np.mean(a,axis=0
文件中有本文的ipynb代码更完整