Table of Contents
Use List to create an array
Use the array function to create an array
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.
How to create an array in Numpy
Home Backend Development Python Tutorial Detailed explanation of array creation in Python NumPy tutorial

Detailed explanation of array creation in Python NumPy tutorial

Aug 26, 2022 am 11:59 AM
python

[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"]
Copy after login
# 用于创建数组的 Python 程序
 
# 使用列表创建数组
    arr=[1, 2, 3, 4, 5]
    for i in arr:
        print(i)
Copy after login

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")
Copy after login

Output:

##The new created array is : 1 2 3 1 5

Creating arrays using numpy methods

NumPy 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)
Copy after login

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)
Copy after login

Output:

Matrix b :

[0 0]

Matrix a :
[[0 0 ]
[0 0]]

Matrix c :
[[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0 .]]

Reshape the array

We can use the

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).

The only required condition is: a1 x a2 x a3 … x aN = b1 x b2 x b3 … x bM. (That is, the original size of the array remains unchanged.)

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)
Copy after login

Output:

Original array :

[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]]]

To create numerical sequences, NumPy provides a function similar to range, which returns an array instead of a list.

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")
Copy after login

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))
Copy after login

Output:

B

(array([ 2. , 2.25, 2.5 , 2.75, 3. ]), 0.25)

A
[0. 929743]

Flat array

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)
Copy after login
Output:

[1, 2, 3, 4]
[1, 3, 2, 4]

How to create an array in Numpy

Returns an array of the same shape and type as the given arrayReturns a new array of the given shape and type, filled with zerosReturns the same as given A given array has an array of zeros of the same shape and type Returns a full array of the same shape and type as the given array. Create an arrayConvert input to array Convert input to ndarray, but pass ndarray subclassesReturns a contiguous array in memory (C order) Interprets input as a matrixReturns an array copy of the given objectInterprets the buffer as a one-dimensional arrayConstruct an array from data in a text or binary fileBy Execute a function on each coordinate to construct an array Create a new one-dimensional array from an iterable objectNew one-dimensional array initialized from text data in stringLoad from text file DataReturns evenly spaced values ​​within a given intervalReturns uniformly distributed numbers within the specified time intervalReturns uniformly distributed numbers on a logarithmic scale Returns numbers uniformly distributed on a logarithmic scale (geometric series) Return the coordinate matrix from the coordinate vectornd_grid instance, which returns a dense multi-dimensional "grid"nd_grid instance, which returns an open multidimensional "meshgrid" Extract diagonals Or construct a diagonal arrayCreate a two-dimensional array with flattened input as diagonalAn array with one at and below a given diagonal and zeros elsewhereLower triangle of array##triu()Upper triangle of arrayvander()Generate Vandermonde matrix[Related recommendations: ]
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
ones() Returns a given shape and type, filled with one_like()
zeros()
zeros_like()
full_like()
array()
asarray()
asanyarray()
ascontiguousarray()
asmatrix()
copy()
frombuffer()
fromfile()
fromfunction()
fromiter()
fromstring()
loadtxt()
arange()
linspace()
logspace()
geomspace()
meshgrid()
mgrid()
ogrid()
diag()
diagflat()
tri()
tril()
##mat() Interpret input as matrix
bmat() Construct a matrix object from a string, nested sequence or array
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!

Statement of this Website
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

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

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles