当前位置:网站首页>Numpy array: join, flatten, and add dimensions
Numpy array: join, flatten, and add dimensions
2022-06-28 09:41:00 【Watermelon】
up to now , We have learned how to create an array and how to set up an array in the tutorial numpy Arrays apply numerical operations . If we use numpy Programming , We will reach this point sooner or later , We will need functions to manipulate the shape or dimension of the array . We will also learn how to join arrays . Besides , We will demonstrate the possibility of adding dimensions to existing arrays and how to stack multiple arrays . We will conclude this chapter by showing an easy way to construct a new array by repeating an existing array .
1 Flatten and reshape the array
There are two ways to flatten multidimensional arrays :flatten() and ravel().
1.1 flatten()
flatten Is a parameter with optional keywords “order” Of ndarry Method . order It can be worth “C”、“F” and “A”. The default value for the sequence is “C”. “C” Indicates flattening in row priority C style , The rightmost index “ Change the fastest ”, Or to put it another way : In row priority , The row index changes the slowest , Column index changes the fastest , therefore a[0,1] With the a[0,0] after .“F” representative Fortran Column prioritization . “A” Express reservation C/Fortran The order .
import numpy as np
import numpy as np
A = np.array([[[0, 1],
[2, 3],
[4, 5],
[6, 7]],
[[8, 9],
[10, 11],
[12, 13],
[14, 15]],
[[16, 17],
[18, 19],
[20, 21],
[22, 23]]])
Flattened_X = A.flatten()
print(Flattened_X)
print(A.flatten(order="C"))
print(A.flatten(order="F"))
print(A.flatten(order="A"))
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
Output :

1.2 ravel()
ravel Returns a flat one-dimensional array . Make copies only when needed . Optional keyword parameters “order” It can be “C”、“F”、“A” or “K”
- 'C': class C The order of , The last axis index changes the fastest , Back to the first axis, the index changes the slowest . “C” Is the default value !
- 'F': similar Fortran Index order of , The first index changes the fastest , The last index changes the slowest .
- 'A': If the array “a” In memory is Fortran Successive , It's like Fortran Index order of , Otherwise, it's like C The order of .
- 'K': Read the elements in the order they appear in memory , Except to reverse the data when the stride is negative .
print(A.ravel(order="A"))
print(A.ravel(order="F"))
print(A.ravel(order="A"))
print(A.ravel(order="K"))
- 1.
- 2.
- 3.
- 4.
Output :

1.3 reshape()
reshape() Method provides a new shape for the array without changing its data , That is, it returns a new array with a new shape .
reshape(a, newshape, order='C')
- ‘a’: An array that needs to be reshaped .
- ‘newshape’: Integer or integer tuple .
- ‘order’:'C', 'F', ‘A’, And flatten And ravel The same parameters as .
X = np.array(range(24))
Y = X.reshape((3, 4, 2))
- 1.
- 2.
Output :

2 Linked array
In the following example , We concatenate three one-dimensional arrays into an array . The elements of the second array are appended to the first array . After that, append the elements of the third array :
x = np.array([11, 22])
y = np.array([18, 7, 6])
z = np.array([1, 3, 5])
c = np.concatenate((x, y, z))
print(c)
- 1.
- 2.
- 3.
- 4.
- 5.
Output :

If we join multidimensional arrays , We can connect arrays by axis . An array must have the same shape to match concatenate() Connect . In the case of multidimensional arrays , We can arrange them by axis . The default value is axis = 0:
x = np.array(range(24))
x = x.reshape((3, 4, 2))
y = np.array(range(100, 124))
y = y.reshape((3, 4, 2))
z = np.concatenate((x, y))
print(z)
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
Output :


We use now axis=1 Make the same connection :
z = np.concatenate((x, y), axis=1)
- 1.
Output :


3 Add new dimension
You can use slicing and np.newaxis Add a new dimension to the array . We use an example to illustrate this technique :
x = np.array([2, 5, 18, 14, 4])
y = x[:, np.newaxis]
print(y)
- 1.
- 2.
- 3.
Output :

4 Vector stacking
A = np.array([3, 4, 5])
B = np.array([1, 9, 0])
print(np.row_stack((A, B)))
print(np.column_stack((A, B)))
- 1.
- 2.
- 3.
- 4.
Output :

A = np.array([[3, 4, 5],
[1, 9, 0],
[4, 6, 8]])
print(np.column_stack((A, A, A)))
print(np.column_stack(A))
- 1.
- 2.
- 3.
- 4.
- 5.
Output :

print(A[0])
print(np.column_stack((A[0], A[0], A[0])))
- 1.
- 2.
Output :

print(np.dstack((A, A, A)))
- 1.
Output :

5 Repetition mode ,“ tile ” Method
Sometimes , You want or must create a new matrix by repeating the existing matrix many times , To create new matrices with different shapes and even sizes . for example , You might have a one-dimensional array array([ 3.4]) And you want to convert it to an array array([ 3.4, 3.4, 3.4, 3.4, 3.4]). In another use case , You might have a two-dimensional array , for example np.array([ [1, 2], [3, 4]]), You intend to use it as a building block to construct shapes as (6, 8):
array([[1, 2, 1, 2, 1, 2, 1, 2],
[3, 4, 3, 4, 3, 4, 3, 4],
[1, 2, 1, 2, 1, 2, 1, 2],
[3, 4, 3, 4, 3, 4, 3, 4],
[1, 2, 1, 2, 1, 2, 1, 2],
[3, 4, 3, 4, 3, 4, 3, 4]])
The construction idea is shown in the figure below :

If this reminds you of tiling the bathroom or kitchen , Then you are on the right track :Numpy The functionality provided for this task is called “ ceramic tile ”.tile The formal syntax for is as follows :
np.tile(A, reps)
- 1.
By way of A The number of repetitions is determined by reps Given the number of times to construct an array .
“reps” It's usually a tuple ( Or list ), It defines along the corresponding axis / The number of repetitions of the direction . for example , If we were to reps Set to (3, 4), be A Will target “ That's ok ” repeat 3 Time , Repeat in the direction of the column 4 Time . We demonstrate this in the following example :
import numpy as np
x = np.array([[1, 2], [3, 4]])
print(np.tile(x, (3, 4)))
- 1.
- 2.
- 3.
Output :

x = np.array([3.4])
y = np.tile(x, (5,))
print(y)
- 1.
- 2.
- 3.
Output :

In front of tile Example , We can also write y = np.tile(x, 5).
If “reps” The length of is n, Then the dimension of the result array will be n and A.ndim The maximum of .
If 'A.ndim < n, By adding a new axis 'A' Upgrade to n dimension . So shape (5,) The array is promoted to (1, 5) be used for 2-D Copy , Or shape (1, 1, 5) be used for 3-D Copy . If this is not the behavior required , Please manually set... Before calling this function “A” Upgrade to n dimension .
If 'A.ndim > d','reps' Promoted to 'A'.ndim, The method is to add 1. So for the shape (2, 3, 4, 5) Array of 'A','reps' ' Of (2, 2) Be regarded as (1, 1, 2, 2). Further examples :
x = np.array([[1, 2], [3, 4]])
print(np.tile(x, 2))
- 1.
- 2.
Output :

x = np.array([[1, 2], [3, 4]])
print(np.tile(x, (2, 1)))
- 1.
- 2.
Output :

x = np.array([[1, 2], [3, 4]])
print(np.tile(x, (2, 2)))
- 1.
- 2.
Output :

边栏推荐
- Which securities company is better and safer to choose when opening an account for the inter-bank certificate of deposit fund with mobile phone
- Fastjason filter field
- ==和eqauls()的区别
- Prototype chain JS
- 线程的生命周期
- When the interviewer asks you to write binarysort in two ways
- 买卖股票费用计算
- Basic content learning of software testing (I)
- 自定义异常类及练习
- Unity 从服务器加载AssetBundle资源写入本地内存,并将下载保存的AB资源从本地内存加载至场景
猜你喜欢

HDI blind hole design, have you noticed this detail?
![1180: fractional line delimitation /p1068 [noip2009 popularization group] fractional line delimitation](/img/1a/162b060a6498e58278b6ca50e4953c.png)
1180: fractional line delimitation /p1068 [noip2009 popularization group] fractional line delimitation

How to reduce the risk of project communication?

Unity AssetBundle资源打包与资源加载

For the development of short video app, the elder warned me to choose the open source code

Calcul des frais d'achat et de vente d'actions

JDBC connection database (MySQL) steps

1181:整数奇偶排序

Automatic conversion - interview questions

自动转换之-面试题
随机推荐
RESTful风格
Write a simple timeline
Dolphin scheduler uses system time
[ybtoj advanced training guide] maximum separation [hash] [Floyd]
The digital human industry is about to break out. What is the market pattern?
浅谈小程序对传媒行业数字化的影响
JVM family (2) - garbage collection
1180: fractional line delimitation /p1068 [noip2009 popularization group] fractional line delimitation
Illustration of MySQL binlog, redo log and undo log
在本类私有属性直接使用?new()在使用!!!
spark的资源调度和任务调度
JSON数据与List集合之间的正确转换
Stutter participle_ Principle of word breaker
Two interview demo
Abnormal occurrence and solution
线程和进程
The private attribute of this class can be used directly? New() in use!!!
Unity 从服务器加载AssetBundle资源写入本地内存,并将下载保存的AB资源从本地内存加载至场景
Prototype chain JS
Which securities company is better and safer to choose when opening an account for the inter-bank certificate of deposit fund with mobile phone