This article mainly introduces a simple example of numpy array splicing, including an introduction to numpy arrays, properties of numpy arrays, etc. It has certain reference value and friends in need can refer to it.
NumPy array is a multidimensional array object called ndarray. It consists of two parts:
·The actual data
·Metadata describing these data
Most operations Only for metadata, without changing the underlying actual data.
There are a few things you need to know about NumPy arrays:
·The subscripts of NumPy arrays start from 0.
·The types of all elements in the same NumPy array must be the same.
NumPy array properties
Before introducing NumPy arrays in detail. First, let’s introduce the basic properties of NumPy arrays in detail. The dimensionality of a NumPy array is called rank. A one-dimensional array has a rank of 1, a two-dimensional array has a rank of 2, and so on. In NumPy, each linear array is called an axis (axes), and the rank actually describes the number of axes. For example, a two-dimensional array is equivalent to two one-dimensional arrays, where each element in the first one-dimensional array is another one-dimensional array. So a one-dimensional array is the axes (axes) in NumPy. The first axis is equivalent to the underlying array, and the second axis is the array in the underlying array. The number of axes, the rank, is the dimension of the array.
The more important ndarray object attributes in NumPy arrays are:
1.ndarray.ndim: The dimension of the array (that is, the number of array axes), which is equal to the rank. The most common is a two-dimensional array (matrix).
2.ndarray.shape: Dimensions of the array. is a tuple of integers representing the size of the array in each dimension. For example, in a two-dimensional array, it represents the "number of rows" and "number of columns" of the array. ndarray.shape returns a tuple whose length is the number of dimensions, that is, the ndim attribute.
3.ndarray.size: The total number of array elements is equal to the product of the tuple elements in the shape attribute.
4.ndarray.dtype: An object representing the type of elements in the array. You can use standard Python types to create or specify dtype. In addition, you can also use the data types provided by NumPy introduced in the previous article.
5.ndarray.itemsize: The byte size of each element in the array. For example, the itemsiz attribute value of an array whose element type is float64 is 8 (float64 occupies 64 bits, and each byte is 8 in length, so 64/8 takes up 8 bytes). Another example is an array whose element type is complex32. The array item attribute is 4 (32/8).
6.ndarray.data: Buffer containing actual array elements. Since elements are generally obtained through the index of the array, there is usually no need to use this attribute.
Array splicing method one
Idea: first convert the array into a list, and then use the list splicing functions append() and extend() Wait for splicing processing, and finally convert the list into an array.
Example 1:
>>> import numpy as np >>> a=np.array([1,2,5]) >>> b=np.array([10,12,15]) >>> a_list=list(a) >>> b_list=list(b) >>> a_list.extend(b_list) >>> a_list [1, 2, 5, 10, 12, 15] >>> a=np.array(a_list) >>> a array([ 1, 2, 5, 10, 12, 15])
This method is only suitable for simple one-dimensional array splicing, because the conversion process is very It is time-consuming and is generally not recommended for splicing large amounts of data.
Array splicing method two
Idea: numpy provides the numpy.append(arr, values, axis=None) function. For parameter specifications, there must be either one array and one value; or two arrays. Three or more arrays cannot be directly appended and spliced. The append function always returns a one-dimensional array.
Example 2:
>>> a=np.arange(5) >>> a array([0, 1, 2, 3, 4]) >>> np.append(a,10) array([ 0, 1, 2, 3, 4, 10]) >>> a array([0, 1, 2, 3, 4]) >>> b=np.array([11,22,33]) >>> b array([11, 22, 33]) >>> np.append(a,b) array([ 0, 1, 2, 3, 4, 11, 22, 33]) >>> a array([[1, 2, 3], [4, 5, 6]]) >>> b=np.array([[7,8,9],[10,11,12]]) >>> b array([[ 7, 8, 9], [10, 11, 12]]) >>> np.append(a,b) array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
numpy array does not have the function of dynamically changing the size, numpy.append() function Each time the entire array is reallocated and the original array is copied to the new array.
Array splicing method three
Idea: numpy provides numpy.concatenate((a1,a2,...),axis=0 )function. Able to complete the splicing of multiple arrays at one time. Where a1, a2,... are parameters of array type
Example 3:
>>> a=np.array([1,2,3]) >>> b=np.array([11,22,33]) >>> c=np.array([44,55,66]) >>> np.concatenate((a,b,c),axis=0) # 默认情况下,axis=0可以不写 array([ 1, 2, 3, 11, 22, 33, 44, 55, 66]) #对于一维数组拼接,axis的值不影响最后的结果 >>> a=np.array([[1,2,3],[4,5,6]]) >>> b=np.array([[11,21,31],[7,8,9]]) >>> np.concatenate((a,b),axis=0) array([[ 1, 2, 3], [ 4, 5, 6], [11, 21, 31], [ 7, 8, 9]]) >>> np.concatenate((a,b),axis=1) #axis=1表示对应行的数组进行拼接 array([[ 1, 2, 3, 11, 21, 31], [ 4, 5, 6, 7, 8, 9]])
to numpy. Compare the running time of the two functions append() and numpy.concatenate()
Example 4:
>>> from time import clock as now >>> a=np.arange(9999) >>> b=np.arange(9999) >>> time1=now() >>> c=np.append(a,b) >>> time2=now() >>> print time2-time1 28.2316728446 >>> a=np.arange(9999) >>> b=np.arange(9999) >>> time1=now() >>> c=np.concatenate((a,b),axis=0) >>> time2=now() >>> print time2-time1 20.3934997107
It can be seen that concatenate() is more efficient and suitable for large-scale data splicing
Summary
The above is a simple example of numpy array splicing in this article All the content, I hope it will be helpful to everyone. Interested friends can continue to refer to this site:
Related recommendations:
Python programming for numpy Example of a method for adding a column to a matrix
Python’s method of creating a symmetric matrix based on the numpy module
The above is the detailed content of Simple example of numpy array splicing_python. For more information, please follow other related articles on the PHP Chinese website!

The basic syntax for Python list slicing is list[start:stop:step]. 1.start is the first element index included, 2.stop is the first element index excluded, and 3.step determines the step size between elements. Slices are not only used to extract data, but also to modify and invert lists.

Listsoutperformarraysin:1)dynamicsizingandfrequentinsertions/deletions,2)storingheterogeneousdata,and3)memoryefficiencyforsparsedata,butmayhaveslightperformancecostsincertainoperations.

ToconvertaPythonarraytoalist,usethelist()constructororageneratorexpression.1)Importthearraymoduleandcreateanarray.2)Uselist(arr)or[xforxinarr]toconvertittoalist,consideringperformanceandmemoryefficiencyforlargedatasets.

ChoosearraysoverlistsinPythonforbetterperformanceandmemoryefficiencyinspecificscenarios.1)Largenumericaldatasets:Arraysreducememoryusage.2)Performance-criticaloperations:Arraysofferspeedboostsfortaskslikeappendingorsearching.3)Typesafety:Arraysenforc

In Python, you can use for loops, enumerate and list comprehensions to traverse lists; in Java, you can use traditional for loops and enhanced for loops to traverse arrays. 1. Python list traversal methods include: for loop, enumerate and list comprehension. 2. Java array traversal methods include: traditional for loop and enhanced for loop.

The article discusses Python's new "match" statement introduced in version 3.10, which serves as an equivalent to switch statements in other languages. It enhances code readability and offers performance benefits over traditional if-elif-el

Exception Groups in Python 3.11 allow handling multiple exceptions simultaneously, improving error management in concurrent scenarios and complex operations.

Function annotations in Python add metadata to functions for type checking, documentation, and IDE support. They enhance code readability, maintenance, and are crucial in API development, data science, and library creation.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 English version
Recommended: Win version, supports code prompts!

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.
