赞
踩
本文是我在学习期间的笔记,看的书是《Python数据分析基础教程 NumPy学习指南 》第二版。
转载请注明出处,谢谢。
本文链接 https://blog.csdn.net/Ming2017123123/article/details/97620925
numpy数组在数值运算方面的效率优于python提供的list容器。
def python_sum(n): a = list(range(n)) b = list(range(n)) c = [] for i in range(len(a)): a[i] = pow(i,2) b[i] = pow(i,3) c.append(a[i] + b[i]) return c def numpy_sum(n): import numpy as np a = pow(np.arange(n), 2) b = pow(np.arange(n), 3) c = a + b return c def test(size): # size = int(sys.argv[1]) # size = 1000 from datetime import datetime import sys start = datetime.now() c = python_sum(size) delta = datetime.now() - start print("The last 2 elements of the sum: ", c[-2:]) print("PythonSum elapsed time in microseconds: ", delta.microseconds) start = datetime.now() c = numpy_sum(size) delta = datetime.now() - start print("The last 2 elements of the sum: ", c[-2:]) print("NumPySum elapsed time in microseconds: ", delta.microseconds) test(100000)
两者的输出形式上有差异:numpysum 的输出不包含逗号,numpy的数组对象以专门的数据结构来存储数值。
大部分操作仅仅修改元数据,而不改变底层的实际数据。
from numpy import *
a = arange(50)
print(a.dtype)
print(a.shape) # 返回一个表示数组维度的tuple
# 创建多维数组
b = array([arange(5), arange(5)])
print(b,"\n",b.dtype,"维度: ",b.shape)
print("选取[1,2]: \n\t", b[1,2])
arange(8,dtype = float64)
array(6).dtype.itemsize
先定义一个数组
a = arange(24).reshape(2,3,4)
a
a.ravel()
a.flatten()
a
a.shape = (6,4)
a
a.transpose()
a.resize(2,12)
a
from numpy import *
a = arange(9).reshape(3,3)
b = a * 2
print("a = \n",a,"\nb = \n",b)
hstack((a,b))
concatenate((a,b), axis=1)
vstack((a,b))
concatenate((a,b),axis=0)
dstack((a,b))
column_stack((a, b)) == hstack((a, b))
row_stack((a, b)) == vstack((a, b))
hsplit(a,3)
split(a,3,axis=1)
vsplit(a,3)
split(a,3,axis=0)
c = arange(27).reshape(3,3,3)
print("c = \n", c)
print("\ndsplit = ",dsplit(c,3))
除了shape和dtype属性外,ndarray对象还有其他许多属性。
b.ndim
b.size
b.itemsize
b.nbytes
b.T
c = array([1.j + 1, 2j + 3])
print("c.real = ",c.real, "\n,c.imag = ",c.imag)
f = b.flat
for i in f:
print(i)
b = arange(4).reshape(2, 2)
print("b = ",b)
print("b.flat[2] = ",b.flat[2])
print("b.flat[[1,3]] = ",b.flat[[1,3]])
b.flat = 7
print("b = ",b)
b.flat[[1,3]] = 1
print("b = ", b)
c = array([ 1 + 1.j, 3. + 2.j])
c.tolist()
print("c = ",c)
print("c.astype(int) = ", c.astype(int))
print("c.astype('complex') = ", c.astype('complex'))
import os
import numpy as np
i2 = np.eye(2)
print('i2 = ',i2)
np.savetxt('eye2.txt',i2)
print(os.path.exists('eye2.txt'))
通用函数 universal functions 即 ufuncs
矩阵是ndarray的子类,可以由专门的字符串格式来创建。
二维的
mat, matrix, bmat 函数来创建矩阵
from numpy import *
A = mat('1 2 3; 4 5 6; 7 8 9')
print("Creating from string: ", A)
mat(arange(9).reshape(3,3))
A.T
A.I
import numpy as np
A = np.eye(2)
print("A",A)
B = 2 * A
print("B", B)
np.bmat("A B; A B")
def ultimate_answer(a):
result = np.zeros_like(a)
result.flat = 42
return result
ufunc = np.frompyfunc(ultimate_answer, 1, 1)
print("The answer : ", ufunc(np.arange(4)))
print("The answer : ", ufunc(np.arange(4).reshape(2,2)))
a = np.arange(9)
print("Reduce",np.add.reduce(a))
np.add.accumulate(a)
print("Reduceat", np.add.reduceat(a, [0, 5, 2, 7]))
# 相当于
print("Reduceat step I", np.add.reduce(a[0:5]))
print("Reduceat step II", a[5])
print("Reduceat step III", np.add.reduce(a[2:7]))
print("Reduceat step IV", np.add.reduce(a[7:]))
np.add.outer(np.arange(3), a)
import numpy as np
a = np.array([2,3,4])
b = np.array([1,2,3])
print("Divide",np.divide(a,b),"\n",np.divide(b,a))
print("True Divide",np.true_divide(a,b),"\n",np.true_divide(b,a))
print("Floor Divide",np.floor_divide(a,b),"\n",np.floor_divide(b,a))
print("/ operator", a/b,"\n",b/a)
print("// operator", a//b, "\n", b//a)
a = np.arange(-4,4)
print("a = ",a)
print("Remainder",np.remainder(a,2))
np.mod(a,2)
a % 2
np.fmod(a,2)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。