numpy数组的创建

1、什么是numpy

我们为什么需要学习numpy?

  • 快速
  • 方便
  • 科学计算的基础库

numpy是个什么东东呢?

一个在Python中做科学计算的基础库,重在数值计算,也是大部分PYTHON科学计算库的基础库,多用于在大型、多维数组上执行数值运算

2、numpy创建数组

import numpy as np

# 使用numpy创建数组,得到ndarray的类型
t1 = np.array([1, 2, 3])
print(t1)
print(type(t1))

t2 = np.array(range(10))
print(t2)
print(type(t2))

t3 = np.arange(10)
print(t3)
print(type(t3))

t4 = np.arange(4, 10, 2)
print(t4)
print(type(t4))

[1 2 3]
<class 'numpy.ndarray'>

[0 1 2 3 4 5 6 7 8 9]
<class 'numpy.ndarray'>

[0 1 2 3 4 5 6 7 8 9]
<class 'numpy.ndarray'>

[4 6 8]
<class 'numpy.ndarray'>

3、numpy中常见的更多数据类型

image.png

4、数据类型的操作

import numpy as np
import random

# numpy中的数据类型
t1 = np.array(range(5), dtype="float32")
print(t1)
print(t1.dtype)

# numpy中的bool类型
t2 = np.array([0, 1, 1, 1, 0, 0], dtype="bool")
print(t2)
print(t2.dtype)

# 调整数据类型
t3 = t2.astype("int8")
print(t3)
print(t3.dtype)

# numpy中的小数
t4 = np.array([random.random() for i in range(10)])
print(t4)
print(t4.dtype)

# 保留固定位小数(此处保留2位小数)
t5 = np.round(t4, 2)
print(t5)

[0. 1. 2. 3. 4.]
float32

[False True True True False False]
bool

[0 1 1 1 0 0]
int8

[0.47948998 0.92815333 0.5632366 0.23592923 0.51608841 0.7394076
0.44955187 0.12145028 0.56799712 0.18678703]
float64

[0.48 0.93 0.56 0.24 0.52 0.74 0.45 0.12 0.57 0.19]

原文地址:https://www.cnblogs.com/wangzheming35/p/15329407.html