Python中的NumPy(一)——基础(Basics)

版权声明:本文版权归作者所有,未经允许不得转载! https://blog.csdn.net/m0_37827994/article/details/86493036

NumPy基础

  • NumPy中的数组是从0开始计算的,即 x[0]
import numpy as np
# Set seed for reproducibility
np.random.seed(seed=1234)

1、标量(0维数组)

  • 标量就是简简单单一个数(0维数组放在0个中括号内)
  • 标量没有维度
  • shape是指形状,因为标量没有维度,所以也就没有形状
  • size是指有几个数
# Scalars
x = np.array(6) # scalar
print ("x: ", x)
# Number of dimensions
print ("x ndim: ", x.ndim)
# Dimensions
print ("x shape:", x.shape)
# Size of elements
print ("x size: ", x.size)
# Data type
print ("x dtype: ", x.dtype)

输出结果:

x:  6
x ndim:  0
x shape: ()
x size:  1
x dtype:  int64

2、一维数组

  • 一维数组放在 [ ] 中(一个中括号)
  • 一维数组dim是1
  • 一维数组行是一行已经固定,所以不用写;列的话本体为3,所以shape是3
  • size就是数组中一共有多少数
# 1-D Array
x = np.array([1.3 , 2.2 , 1.7])
print ("x: ", x)
print ("x ndim: ", x.ndim)
print ("x shape:", x.shape)
print ("x size: ", x.size)
print ("x dtype: ", x.dtype) # notice the float datatype

输出结果:

x:  [1.3 2.2 1.7]
x ndim:  1
x shape: (3,)
x size:  3
x dtype:  float64

3、二维数组

  • 二维数组放在 [ [ ] ] (两个中括号中) ;[ ] 外的逗号表示换行
  • 二维数组dim为2
  • shape是3行3列
  • size就是矩阵中一共有多少数
# 2-D array 
x = np.array([[1,2,3], [4,5,6], [7,8,9]])
print ("x:\n", x)
print ("x ndim: ", x.ndim)
print ("x shape:", x.shape)
print ("x size: ", x.size)
print ("x dtype: ", x.dtype)

输出结果:

x:
 [[1 2 3]
 [4 5 6]
 [7 8 9]]
x ndim:  2
x shape: (3, 3)
x size:  9
x dtype:  int32

4、三维数组(矩阵)

  • 三维数组放在 [ [ [ ] ] ] (三个中括号中) ;[ ] 外的逗号表示换行
  • 三维数组dim为3
  • shape是(1,3,3):第二个大括号中共1个,这一个是3行3列
  • size就是矩阵中一共有多少数
# 3-D array (matrix)
x = np.array([[[1,2,3], [4,5,6], [7,8,9]]])
print ("x:\n", x)
print ("x ndim: ", x.ndim)
print ("x shape:", x.shape)
print ("x size: ", x.size)
print ("x dtype: ", x.dtype)

输出结果:

x:
 [[[1 2 3]
  [4 5 6]
  [7 8 9]]]
x ndim:  3
x shape: (1, 3, 3)
x size:  9
x dtype:  int64

5、函数

# Functions
print ("np.zeros((2,2)):\n", np.zeros((2,2)))
print ("np.ones((2,2)):\n", np.ones((2,2)))
print ("np.eye((2)):\n", np.eye((2)))
print ("np.random.random((2,2)):\n", np.random.random((2,2)))

输出结果:

np.zeros((2,2)):
 [[0. 0.]
 [0. 0.]]
np.ones((2,2)):
 [[1. 1.]
 [1. 1.]]
np.eye((2)):
 [[1. 0.]
 [0. 1.]]
np.random.random((2,2)):
 [[0.19151945 0.62210877]
 [0.43772774 0.78535858]]

注:一些关于NumPy的参考资料:
https://www.numpy.org.cn/article/basics/an_introduction_to_scientific_python_numpy.html

猜你喜欢

转载自blog.csdn.net/m0_37827994/article/details/86493036