numpy - array

Table of contents

1. Create a simple array

1.1 Brute force construction method

1.2 Special numerical method

1.3 Random numerical method

1.4 Fixed-length division method

2. Create complex arrays

2.1 Repeated construction method

2.2 Grid construction method

2.3 Draw 3D graphics


Methods of creating arrays are divided into two categories: creating simple arrays and constructing complex arrays. In fact, there is no strict dividing line between simple arrays and complex arrays. Generally speaking, arrays created out of nothing are called simple arrays, and arrays created through grafting and inferences are called complex arrays.

1. Create a simple array

The methods used to construct simple arrays can be divided into four categories, namely brute force construction method, special numerical method, random numerical method and fixed-length division method.

1.1 Brute force construction method

The brute force construction method uses np.array() to create an array. The standard writing method is:

a = np.array(object, dtype=None, copy=True, order=None, subok=False, ndmin=0)

Whatever structure you want, just use a list or tuple to express it:

a = np.array([[1,2,3],
            [4,5,6]]
             )
a = np.array(((1,2,3),
              (4,5,6)))

1.2 Special numerical method

Special values ​​generally refer to 0, 1, null, etc. Special numerical methods are suitable for constructing all 0s, all 1s, empty arrays, or similar identity matrices composed of 0s and 1s, such as an array with 1s on the main diagonal and 0s on the rest.

The functions that can be used are:


numpy.zeros(shape, dtype=float, order=‘C’)  0数组
numpy.ones(shape, dtype=float, order=‘C’)    1数组
numpy.empty(shape, dtype=float, order=‘C’)   空数组,但是要指明数据类型
numpy.eye(N, M=None, k=0, dtype=float, order='C’)   单位矩阵

For example:

print(np.zeros((3,3),dtype=float))
print(np.ones((3,3),dtype=int))
print(np.empty((3,3)))
print(np.empty((3,3),dtype=bool))
print(np.eye(3,3))

You can also use the fill method to fill the array into the moment array.

a = np.empty((3,3))
a.fill(4)
print(a)

[[4. 4. 4.]
 [4. 4. 4.]
 [4. 4. 4.]]

1.3 Random numerical method

NumPy also has a random submodule, which uses random numerical methods to create arrays. The main purpose is to use the random submodule. Commonly used modules are:

random() generates random floating-point numbers in the interval [0,1); randint() generates random integers in the interval [low, high); normal() generates a normal distribution with loc as the mean and scale as the standard deviation. array

numpy.random.random(size=None)
numpy.random.randint(low, high=None, size=None, dtype=‘l’)
numpy.random.normal(loc=0.0, scale=1.0, size=None)

For example:

print(np.random.random(5))
print(np.random.randint(low=1,high=10,size =(3,3)))

Before experiencing normal, let’s introduce matplotlib’s hist method:

plt.hist(x, bins=10, range=None, normed=False, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=False, color=None, label=None, stacked=False)

参数:
x:指定要绘制直方图的数据;
bins:指定直方图条形的个数;
range:指定直方图数据的上下界,默认包含绘图数据的最大值和最小值;
density:是否将直方图的频数转换成频率;
weights:该参数可为每一个数据点设置权重;
cumulative:是否需要计算累计频数或频率;
bottom:可以为直方图的每个条形添加基准线,默认为0;
histtype:指定直方图的类型,默认为bar,除此还有’barstacked’, ‘step’, ‘stepfilled’;
align:设置条形边界值的对其方式,默认为mid,除此还有’left’和’right’;
orientation:设置直方图的摆放方向,默认为垂直方向;
rwidth:设置直方图条形宽度的百分比;
log:是否需要对绘图数据进行log变换;
color:设置直方图的填充色;
label:设置直方图的标签,可通过legend展示其图例;
stacked:当有多个数据时,是否需要将直方图呈堆叠摆放,默认水平摆放
import matplotlib.pyplot as plt

data = np.random.normal(loc=100,scale=1,size=10000)
plt.hist(data,bins = 1000)
plt.show()

1.4 Fixed-length division method

The most commonly used function for fixed-length division method is arange(), and another fixed-length division function linspace().

The function prototype is:

a = np.arange(0,15,1).reshape((3,5))
print(a)

```python
a = np.arange(0,15,1).reshape((3,5))
print(a)
```

The linspace() function requires 3 parameters: a starting point, an end point, and the number of returned elements. The elements returned by linspace() include the starting point and the end point. We can choose whether to include the end point through the endpoint parameter.

Numpy provides the linspace function (sometimes also called np.linspace), which is a tool for creating numerical sequences in Python. Similar to Numpy arange, generates a uniformly distributed numerical sequence with a structure similar to a Numpy array.

Create a sequence of values ​​by defining uniform intervals. In fact, you need to specify the starting point and ending end of the interval, and specify the total number of separation values ​​(including the starting point and ending point); the final function returns a uniformly distributed numerical sequence of the interval class

endpoint: whether to include end, the default is True (included),
that is: when endpoint = True, interval = (end-start) / (num-1)
when endpoint = False, interval = (end-start) / num

dtype: Like other NumPy, the dtype parameter in np.linspace determines the data type of the output array. If not specified, Python infers the data type based on other parameter values. It can be specified explicitly if necessary, and the parameter value can be any data type supported by NumPy and Python.

print(np.linspace(0,10,9,endpoint=True))
print(np.linspace(0,10,9,endpoint=False))

2. Create complex arrays

Constructing complex arrays can be divided into two methods: repeated construction method and grid construction method.

2.1 Repeated construction method

The repeat construction method mainly uses two functions, repeat() and tile(). repeat() is used to repeat elements, and tile() is used to repeat arrays.

ar = np.arange(5)
print(np.repeat(ar,2))
print(np.tile(ar,2))
print(np.tile(ar,(5,5))) #重复5行5列

For multidimensional array a, repeat() also has a default parameter axis.

a = np.arange(6).reshape((2,3))
print(a)
print(np.repeat(a,2,axis=0))  #重复每行
print(np.repeat(a,2,axis=1))  #重复列

2.2 Grid construction method

There are generally two ways to use an array to represent a latitude and longitude grid. The first way is represented by two one-dimensional arrays.

lon = np.linspace(-180,180,37) # 网格精度为10°,共计37个经度点
lat = np.linspace(-90,90,19) # 网格精度为10°,共计19个纬度点
print(lon)
print(lat)

The second way is to use np.meshgrid() to generate two two-dimensional arrays, representing the longitude grid and the latitude grid respectively. np.meshgrid() takes the two one-dimensional arrays lon and lat just now as parameters, and the accuracy of the generated grid is also 10°.

np.meshgrid(*xi, **kwargs), returns the coordinate matrix from the coordinate vector, that is, the axis point of the given coordinates, returns a coordinate grid point, for example, given x:n, y:m, it will return A list, the first element represents the x-axis value, and the second element represents the y-axis value. That is, n×m coordinate points.

lons,lats = np.meshgrid(lon,lat)
print(lons,lats)

a = np.array([1,2,3])
# 坐标向量
b = np.array([7,8])
# 从坐标向量中返回坐标矩阵
# 返回list,有两个元素,第一个元素是X轴的取值,第二个元素是Y轴的取值
res = np.meshgrid(a,b)
print(res)

Or use the mgrid method to generate it directly

lats, lons = np.mgrid[-90:91:5., -180:181:5.]  # 网格精度为5°,网格shape为(37,73)
print(lats,lons,sep='\n')

You can also use imaginary numbers to define grid shapes:

lats, lons = np.mgrid[-90:90:37j, -180:180:73j] # 也可以用虚实指定分割点数,网格精度同样为5°
print(lats,lons,sep='\n')

2.3 Draw 3D graphics

radians() method converts angles to radians

lats, lons = np.mgrid[-90:91:5., -180:181:5.]
lons = np.radians(lons) # 度转弧度
lats = np.radians(lats) # 度转弧度
z = np.sin(lats) # 网格上所有点的z坐标
x = np.cos(lats)*np.cos(lons) # 网格上所有点的x坐标
y = np.cos(lats)*np.sin(lons) # 网格上所有点的y坐标
ax = plt.subplot(111,projection='3d')
ax.plot_surface(x,y,z,cmap=plt.cm.coolwarm,alpha=0.8)
plt.show()

Guess you like

Origin blog.csdn.net/longhaierwd/article/details/131776585