内容目录
In [2]:
# Python列表的性能记录
import time
now = lambda: time.time()
t1 = now()
a = []
for x in range(10000):
a.append(x**2)
t2 = now()
print(t2-t1)
0.0013778209686279297
In [3]:
# Numpy的操作性能记录
import time
import numpy as np
now = lambda: time.time()
t3 = now()
b = np.arange(10000)**2
t4 = now()
print(t4-t3)
0.00018906593322753906
Numpy的数组介绍¶
In [5]:
# numpy的数组中的数据类型要一致
import numpy as np
a = [1, 2.3, '4']
b = np.array(a)
print(b)
['1' '2.3' '4']
numpy数组的生成¶
- 使用np.arange创建
- 使用np.random创建
- 使用特殊函数创建
- np.zeros
- np.ones
- np.full
- np.eye
- 使用np.arange转换
In [8]:
# 使用np.arange创建数组
c = np.arange(0, 12, 2)
print(c)
[ 0 2 4 6 8 10]
In [7]:
# 使用np.random
d = np.random.random((2, 3)) # 生成一个2行3列的数组
print(d)
# 使用np.randint
e = np.random.randint(0, 9, size=(4,4,)) #从0,9之间生成4行4列数组
print(e)
[[0.8093922 0.48651887 0.92670766] [0.23147437 0.89693885 0.88318157]] [[8 2 2 6] [2 2 3 0] [8 7 6 1] [2 6 7 3]]
In [9]:
# 使用特殊函数Zeros
array_zero = np.zeros((3, 3))
print(array_zero)
[[0. 0. 0.] [0. 0. 0.] [0. 0. 0.]]
In [10]:
# 使用特殊函数ones
array_ones = np.ones((4, 4))
print(array_ones)
[[1. 1. 1. 1.] [1. 1. 1. 1.] [1. 1. 1. 1.] [1. 1. 1. 1.]]
In [11]:
# 使用特殊函数full
array_full = np.full((2, 3), 9)
print(array_full)
[[9 9 9] [9 9 9]]
In [12]:
# 使用特殊函数eye:生成对称数组
array_eye = np.eye(5)
print(array_eye)
[[1. 0. 0. 0. 0.] [0. 1. 0. 0. 0.] [0. 0. 1. 0. 0.] [0. 0. 0. 1. 0.] [0. 0. 0. 0. 1.]]
数组数据类型dtype¶
In [13]:
import numpy as np
a = np.arange(10)
print(a)
print(a.dtype)
[0 1 2 3 4 5 6 7 8 9] int64
In [14]:
b = np.array([1,2,3,4,5], dtype=np.float16)
print(b)
print(b.dtype)
[1. 2. 3. 4. 5.] float16
In [15]:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
d = np.array([Person('小明', 18), Person('小红', 20)])
print(d)
print(d.dtype)
[<__main__.Person object at 0x116765ad0> <__main__.Person object at 0x113f66a90>] object
In [16]:
f = np.array(['xiaoming', 'xiaohong'], dtype='S')
print(f)
print(f.dtype)
[b'xiaoming' b'xiaohong'] |S8
In [17]:
e = np.array(['a', 'c'],dtype='U')
print(e)
print(e.dtype) # Unicode数据类型
['a' 'c'] <U1