


[Related recommendations: Python3 video tutorial ]
Use List to create an array
Arrays are used in a Multiple values are stored in variables. Python does not have built-in support for arrays, but Python lists can be used instead.
Example:
arr = [1, 2, 3, 4, 5] arr1 = ["geeks", "for", "geeks"]
# 用于创建数组的 Python 程序 # 使用列表创建数组 arr=[1, 2, 3, 4, 5] for i in arr: print(i)
Output:
1
2
3
4
5
Use the array function to create an array
array(data type, value list) The function is used to create an array, specified in its parameters List of data types and values.
Example:
# 演示 array() 工作的 Python 代码 # 为数组操作导入“array” import array # 用数组值初始化数组 # 用有符号整数初始化数组 arr = array.array('i', [1, 2, 3]) # 打印原始数组 print ("The new created array is : ",end="") for i in range (0,3): print (arr[i], end=" ") print ("\r")
Output:
##The new created array is : 1 2 3 1 5Creating arrays using numpy methodsNumPy provides several functions to create arrays with initial placeholder contents. These minimize the need to grow the array, which is an expensive operation. For example: np.zeros, np.empty, etc.
numpy.empty(shape, dtype = float, order = 'C'): Returns a new array of the given shape and type, with random values.
# 说明 numpy.empty 方法的 Python 代码 import numpy as geek b = geek.empty(2, dtype = int) print("Matrix b : \n", b) a = geek.empty([2, 2], dtype = int) print("\nMatrix a : \n", a) c = geek.empty([3, 3]) print("\nMatrix c : \n", c)
Output:
Matrix b :[ 0 1079574528]
Matrix a :
[[0 0 ]
[0 0]]
Matrix a :
[[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0 .]]
numpy.zeros(shape, dtype = None, order = 'C'): Returns a new array of the given shape and type, with zeros.
# 说明 numpy.zeros 方法的 Python 程序 import numpy as geek b = geek.zeros(2, dtype = int) print("Matrix b : \n", b) a = geek.zeros([2, 2], dtype = int) print("\nMatrix a : \n", a) c = geek.zeros([3, 3]) print("\nMatrix c : \n", c)
Output:
Matrix b :Reshape the arrayWe can use the[0 0]
Matrix a :
[[0 0 ]
[0 0]]
Matrix c :
[[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0 .]]
reshape method to reshape the array. Consider an array of shape (a1, a2, a3, ..., aN). We can reshape and convert it into another array of shape (b1, b2, b3, ..., bM).
numpy.reshape(array, shape, order = 'C'): Reshape the array without changing the array data .
# 说明 numpy.reshape() 方法的 Python 程序 import numpy as geek array = geek.arange(8) print("Original array : \n", array) # 具有 2 行和 4 列的形状数组 array = geek.arange(8).reshape(2, 4) print("\narray reshaped with 2 rows and 4 columns : \n", array) # 具有 2 行和 4 列的形状数组 array = geek.arange(8).reshape(4 ,2) print("\narray reshaped with 2 rows and 4 columns : \n", array) # 构造 3D 数组 array = geek.arange(8).reshape(2, 2, 2) print("\nOriginal array reshaped to 3D : \n", array)
Output:
Original array :To create numerical sequences, NumPy provides a function similar to range, which returns an array instead of a list.[0 1 2 3 4 5 6 7]
array reshaped with 2 rows and 4 columns :
[[0 1 2 3]
[4 5 6 7]]
array reshaped with 2 rows and 4 columns :
[[0 1]
[2 3]
[4 5]
[6 7]]
Original array reshaped to 3D :
[[[0 1]
[2 3]]
[[4 5]
[6 7]]]
arange Returns uniformly distributed values within a given interval. StepThe length is specified.
linspace Returns uniformly distributed values within a given interval. The element numbered _ is returned.
arange([start,] stop[, step,][, dtype]): Returns an array with evenly spaced elements based on the interval. The intervals mentioned are half-open, i.e. [start, stop]
# 说明 numpy.arange 方法的 Python 编程 import numpy as geek print("A\n", geek.arange(4).reshape(2, 2), "\n") print("A\n", geek.arange(4, 10), "\n") print("A\n", geek.arange(4, 20, 3), "\n")
Output:
A[[0 1]
[2 3]]
A
[4 5 6 7 8 9]
A
[ 4 7 10 13 16 19]
numpy.linspace(start, stop, num = 50, endpoint = True, retstep = False, dtype = None): Returns numeric space evenly across intervals. Like arange but instead of step it uses sample numbers.
# 说明 numpy.linspace 方法的 Python 编程 import numpy as geek # 重新设置为 True print("B\n", geek.linspace(2.0, 3.0, num=5, retstep=True), "\n") # 长期评估 sin() x = geek.linspace(0, 2, 10) print("A\n", geek.sin(x))
Output:
B(array([ 2. , 2.25, 2.5 , 2.75, 3. ]), 0.25)
Flat array
A
[0. 929743]
We can use the flatten method to make a copy of the array Folded into one dimension. It accepts an order parameter. The default value is "C" (for row-major order). Use "F" for column major order.
numpy.ndarray.flatten(order = 'C') : Returns a copy of the array folded into one dimension. # 说明 numpy.flatten() 方法的 Python 程序
import numpy as geek
array = geek.array([[1, 2], [3, 4]])
# 使用扁平化方法
array.flatten()
print(array)
#使用扁平化方法
array.flatten('F')
print(array)
[1, 2, 3, 4]
[1, 3, 2, 4]How to create an array in Numpy
Function
Description
empty()
Returns a new array of the given shape and type without initialization entry
empty_like()
Returns a new array with the same shape and type as the given array
eye()
Returns a two-dimensional array with 1 on the diagonal and 0 in other positions.
identity()
Returns the identity array
Returns an array of the same shape and type as the given arrayones()
Returns a given shape and type, filled with one_like()
Returns a new array of the given shape and type, filled with zeros
zeros()
Returns the same as given A given array has an array of zeros of the same shape and type
zeros_like()
Returns a full array of the same shape and type as the given array.
full_like()
Create an array
array()
Convert input to array
asarray()
Convert input to ndarray, but pass ndarray subclasses
asanyarray()
Returns a contiguous array in memory (C order)
ascontiguousarray()
Interprets input as a matrix
asmatrix()
Returns an array copy of the given object
copy()
Interprets the buffer as a one-dimensional array
frombuffer()
Construct an array from data in a text or binary file
fromfile()
By Execute a function on each coordinate to construct an array
fromfunction()
Create a new one-dimensional array from an iterable object
fromiter()
New one-dimensional array initialized from text data in string fromstring()
Load from text file Data
loadtxt()
Returns evenly spaced values within a given interval
arange()
Returns uniformly distributed numbers within the specified time interval
linspace()
Returns uniformly distributed numbers on a logarithmic scale
logspace()
Returns numbers uniformly distributed on a logarithmic scale (geometric series)
geomspace()
Return the coordinate matrix from the coordinate vector
meshgrid()
nd_grid instance, which returns a dense multi-dimensional "grid"
mgrid()
nd_grid instance, which returns an open multidimensional "meshgrid"
ogrid()
Extract diagonals Or construct a diagonal array
diag()
Create a two-dimensional array with flattened input as diagonal
diagflat()
An array with one at and below a given diagonal and zeros elsewhere tri()
Lower triangle of array
tril()
##triu() Upper triangle of array
vander() Generate Vandermonde matrix
##mat()
Interpret input as matrix
bmat()
Construct a matrix object from a string, nested sequence or array
[Related recommendations: Python3 video tutorial ]
The above is the detailed content of Detailed explanation of array creation in Python NumPy tutorial. For more information, please follow other related articles on the PHP Chinese website!

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i


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

SublimeText3 Linux new version
SublimeText3 Linux latest version

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

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

Notepad++7.3.1
Easy-to-use and free code editor
