search
HomeBackend DevelopmentPython TutorialIn-depth understanding of NumPy concise tutorial---Array 3 (combination)

The first two articles gave a basic introduction to NumPy arrays. This article provides a more in-depth discussion of NumPy arrays. First, we introduce arrays of custom types, then the combination of arrays, and finally we introduce the issues of array copying.

Custom structure array

Structure types like C language can also be defined through NumPy. The method of defining a structure in NumPy is as follows:

Define the structure type name; define the field name and indicate the field data type.

student= dtype({'names':['name', 'age', 'weight'], 'formats':['S32', 'i','f']}, align = True)

Here student is the name of the custom structure type, created using the dtype function, in the first parameter, 'names' and 'formats 'Cannot be changed. Names listed are the field names in the structure, and formats listed are the data types of the corresponding fields. S32 represents a 32-byte length string, i represents a 32-bit integer, and f represents a 32-bit floating point number. When the last parameter is True, it indicates that memory alignment is required.

NumPy character encoding is used in the field to represent the data type. See the table below for more detailed data types.


##Single precision floating point numberfDouble precision floating point numberdBoolean valuebPluralDStringSUnicodeU VoidV
Data type Character encoding
Integer i
Unsigned integer u
After defining the structure type, you can define the type as an element The array is:


a= array([(“Zhang”, 32, 65.5), (“Wang”, 24, 55.2)], dtype =student)

In addition to listing the data of the corresponding fields in each element, you also need the last parameter in the array function Specify its corresponding data type.

Combining functions

Here are the different ways to combine functions. First create two arrays:


>>> a = arange(9).reshape(3,3) 
>>> a 
array([[0, 1, 2], 
   [3, 4, 5], 
   [6, 7, 8]]) 
>>> b = 2 * a 
>>> b 
array([[ 0, 2, 4], 
  [ 6, 8, 10], 
  [12, 14, 16]])

Horizontal combination

>>> hstack((a, b)) 
array([[ 0, 1, 2, 0, 2, 4], 
  [ 3, 4, 5, 6, 8, 10], 
  [ 6, 7, 8, 12, 14, 16]])

This effect can also be obtained through the concatenate function and specify the corresponding axis:


>>> concatenate((a, b), axis=1) 
array([[ 0, 1, 2, 0, 2, 4], 
  [ 3, 4, 5, 6, 8, 10], 
  [ 6, 7, 8, 12, 14, 16]])

##Vertical Combination


>>> vstack((a, b)) 
array([[ 0, 1, 2], 
  [ 3, 4, 5], 
  [ 6, 7, 8], 
  [ 0, 2, 4], 
  [ 6, 8, 10], 
  [12, 14, 16]])

Similarly, this effect can be obtained through the concatenate function and specifying the corresponding axis.


>>> concatenate((a, b), axis=0) 
array([[ 0, 1, 2], 
  [ 3, 4, 5], 
  [ 6, 7, 8], 
  [ 0, 2, 4], 
  [ 6, 8, 10], 
  [12, 14, 16]])

Depth Combination


In addition, there is also a depth combination function dstack. As the name suggests, it combines on the third axis of the array (i.e. depth). As follows:


>>> dstack((a, b)) 
array([[[ 0, 0], 
  [ 1, 2], 
  [ 2, 4]], 
 
  [[ 3, 6], 
  [ 4, 8], 
  [ 5, 10]], 
 
  [[ 6, 12], 
  [ 7, 14], 
  [ 8, 16]]])

Look carefully and find that the corresponding elements are combined into a new list, which is used as an element of the new array.

Row Combination


Row Combination combines multiple one-dimensional arrays as each row of a new array:


>>> one = arange(2) 
>>> one 
array([0, 1]) 
>>> two = one + 2 
>>> two 
array([2, 3]) 
>>> row_stack((one, two)) 
array([[0, 1], 
  [2, 3]])

For 2D arrays, it works like a vertical combination.

Column combination


The effect of column combination should be clear. As follows:


>>> column_stack((oned, twiceoned)) 
array([[0, 2], 
  [1, 3]])

For 2-dimensional arrays, it works like a horizontal combination.

Split array


In NumPy, the functions for splitting arrays include hsplit, vsplit, dsplit and split. You can split the array into subarrays of the same size, or specify the location where the original array is split.

Horizontal split


##

>>> a = arange(9).reshape(3,3) 
>>> a 
array([[0, 1, 2], 
  [3, 4, 5], 
  [6, 7, 8]]) 
>>> hsplit(a, 3) 
[array([[0], 
  [3], 
  [6]]), 
 array([[1], 
  [4], 
  [7]]), 
 array([[2], 
  [5], 
  [8]])]

Also call the split function and specify the axis as 1 to obtain this effect :


split(a, 3, axis=1)

Vertical segmentation

Vertical segmentation is segmented along the vertical axis Array:


>>> vsplit(a, 3) 
>>> [array([[0, 1, 2]]), array([[3, 4, 5]]), array([[6, 7, 8]])]

Similarly, you can also use the solit function and specify the axis as 1 to achieve this effect:


>>> split(a, 3, axis=0)

Depth-oriented segmentation

The dsplit function uses a depth-oriented segmentation method:


>>> c = arange(27).reshape(3, 3, 3) 
>>> c 
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], 
  [24, 25, 26]]]) 
>>> dsplit(c, 3) 
[array([[[ 0], 
  [ 3], 
  [ 6]], 
 
  [[ 9], 
  [12], 
  [15]], 
 
  [[18], 
  [21], 
  [24]]]), 
 array([[[ 1], 
  [ 4], 
  [ 7]], 
 
  [[10], 
  [13], 
  [16]], 
 
  [[19], 
  [22], 
  [25]]]), 
 array([[[ 2], 
  [ 5], 
  [ 8]], 
 
  [[11], 
  [14], 
  [17]], 
 
  [[20], 
  [23], 
  [26]]])]

Copying and Mirroring (View)

When operating on and processing arrays, their data is sometimes copied to a new array sometimes not. This is often a source of confusion for newbies. There are three cases for this:

No copying at all

Simple assignment without copying array objects or their data.


>>> a = arange(12) 
>>> b = a  #不创建新对象 
>>> b is a   # a和b是同一个数组对象的两个名字 
True 
>>> b.shape = 3,4 #也改变了a的形状 
>>> a.shape 
(3, 4) 
    Python 传递不定对象作为参考4,所以函数调用不拷贝数组。
 >>> def f(x): 
...  print id(x) 
... 
>>> id(a)  #id是一个对象的唯一标识 
148293216 
>>> f(a) 
148293216

View and shallow copy

Different array objects share the same a data. The view method creates a new array object pointing to the same data.


>>> c = a.view() 
>>> c is a 
False 
>>> c.base is a  #c是a持有数据的镜像 
True 
>>> c.flags.owndata 
False 
>>> 
>>> c.shape = 2,6 # a的形状没变 
>>> a.shape 
(3, 4) 
>>> c[0,4] = 1234  #a的数据改变了 
>>> a 
array([[ 0, 1, 2, 3], 
  [1234, 5, 6, 7], 
  [ 8, 9, 10, 11]])

The sliced ​​array returns a view of it:


>>> s = a[ : , 1:3]  # 获得每一行1,2处的元素 
>>> s[:] = 10   # s[:] 是s的镜像。注意区别s=10 and s[:]=10 
>>> a 
array([[ 0, 10, 10, 3], 
  [1234, 10, 10, 7], 
  [ 8, 10, 10, 11]])

Deep copy

This copy method completely copies the array and its data.


 >>> d = a.copy()  #创建了一个含有新数据的新数组对象 
>>> d is a 
False 
>>> d.base is a  #d和a现在没有任何关系 
False 
>>> d[0,0] = 9999 
>>> a 
array([[ 0, 10, 10, 3], 
  [1234, 10, 10, 7], 
  [ 8, 10, 10, 11]])

The above is the entire content of this article. I hope it will be helpful to everyone's learning, and I also hope that everyone will support the PHP Chinese website.

For more in-depth understanding of NumPy’s concise tutorial---Array 3 (combination) related articles, please pay attention to the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version