numpy学习笔记—1.数组的创建
一、数组的创建
(1)创建数组numpy
1.使用np.array([1, 2, 3, 4, 5])创建数组
import numpy as np
t1 = np.array([1, 2, 3, 4, 5])
print(t1)
输出结果:
[1 2 3 4 5]
2.使用np.array(range(1, 10))创建数组
import numpy as np
t2 = np.array(range(1, 10)) # 使用range函数,创建一个从[1,10)的连续数字且步长为1(步长为1:即每隔1个数取一个值,如:1,2,3,4,5,6,7,8,9)
print(t2)
输出结果:
[1 2 3 4 5 6 7 8 9]
3.使用np.arange(1, 10)创建数组
np.arange可以看做是np.array(range())的结合体
import numpy as np
t3 = np.arange(1, 10)
print(t3)
输出结果:
[1 2 3 4 5 6 7 8 9]
(2)查看numpy数组的类型
使用type()函数查看数组类型
import numpy as np
t4 = np.arange(1, 10)
print(type(t4))
输出结果:
<class 'numpy.ndarray'>
(3)查看numpy数组的数据类型
使用.dtype方式查看数据的类型,dtype看做是data type。
import numpy as np
t5 = np.arange(1, 10)
print(t5.dtype)
输出结果:
int64
二、数据类型的操作
(1)创建numpy时指定数据类型
64位的电脑默认是64,32位的电脑默认是32。可以在创建numpy时使用dtype指定数据类型。
1.指定数据类型为float32
import numpy as np
t6 = np.array([1, 2, 3, 4, 5], dtype="float32")
print(t6)
print(t6.dtype)
输出结果:
[1. 2. 3. 4. 5.]
float32
2.指定数据类型为int8
import numpy as np
t7 = np.array([1, 2, 3, 4, 5], dtype="int8")
print(t7)
print(t7.dtype)
输出结果:
[1 2 3 4 5]
int8
(2)修改numpy的数据类型
import numpy as np
t8 = np.array([1, 2, 3, 4, 5], dtype="int32")
print(t8)
print(t8.dtype)
t9 = t8.astype(np.int8)
print(t9.dtype)
输出结果:
[1 2 3 4 5]
int32
int8