Home Backend Development Python Tutorial Summary of simple usage of python numpy

Summary of simple usage of python numpy

Aug 21, 2019 pm 05:59 PM
numpy python

Summary of simple usage of python numpy

Simple usage of Numpy

import numpy as np
Copy after login

1. Create ndarray object

Convert the list to ndarray:

>>> a = [1,2,3,4,5]
>>> np.array(a)
array([1, 2, 3, 4, 5])
Copy after login

Get a random floating point number

>>> np.random.rand(3, 4)
array([[ 0.16215336,  0.49847764,  0.36217369,  0.6678112 ],
     [ 0.66729648,  0.86538771,  0.32621889,  0.07709784],
     [ 0.05460976,  0.3446629 ,  0.35589223,  0.3716221 ]])
Copy after login

Get a random integer

>>> np.random.randint(1, 5, size=(3,4))
array([[2, 3, 1, 2],
     [3, 4, 4, 4],
     [4, 4, 4, 3]])
Copy after login

Get zero

>>> np.zeros((3,4))
array([[ 0.,  0.,  0.,  0.],
     [ 0.,  0.,  0.,  0.],
     [ 0.,  0.,  0.,  0.]])
Copy after login

Get one

>>> np.ones((3,4))
array([[ 1.,  1.,  1.,  1.],
     [ 1.,  1.,  1.,  1.],
     [ 1.,  1.,  1.,  1.]])
Copy after login

Get empty (it’s best not to use it, find out more about it, the versions are different return The values ​​are different)

>>> np.empty((3,4))
array([[ 1.,  1.,  1.,  1.],
     [ 1.,  1.,  1.,  1.],
     [ 1.,  1.,  1.,  1.]])
Copy after login

Take the integer zero or one

>>> np.ones((3,4),int)
array([[1, 1, 1, 1],
       [1, 1, 1, 1],
       [1, 1, 1, 1]])
>>> np.zeros((3,4),int)
array([[0, 0, 0, 0],
       [0, 0, 0, 0],
       [0, 0, 0, 0]])
Copy after login

Imitate the range command to create ndarray:

>>> np.arange(2,10,2) # 开始,结束,步长
array([2, 4, 6, 8])
Copy after login

Related recommendations: "Python Video Tutorial"

2. Viewing and operating ndarray attributes:

Look at ndarray attributes:

>>> a = [[1,2,3,4,5],[6,7,8,9,0]]
>>> b = np.array(a)
>>> b.ndim  #维度个数(看几维)
2
>>> b.shape  #维度大小(看具体长宽)
(5,2)
>>>b.dtype
dtype('int32')
Copy after login

Specify attributes when creating ndarray:

>>> np.array([1,2,3,4,5],dtype=np.float64)
array([ 1.,  2.,  3.,  4.,  5.])
>>> np.zeros((2,5),dtype=np.int32)
array([[0, 0, 0, 0, 0],
     [0, 0, 0, 0, 0]])
Copy after login

Attribute transfer:

>>> a = np.array([1,2,3,4,5],dtype=np.float64)
>>> a
array([ 1.,  2.,  3.,  4.,  5.])
>>> a.astype(np.int32)
array([1, 2, 3, 4, 5])
Copy after login

三, Simple operation:

Batch operation:

>>> a = np.array([1,2,3,4,5],dtype=np.int32)
>>> a
array([1, 2, 3, 4, 5])
>>> a + a
array([ 2,  4,  6,  8, 10])
>>> a * a
array([ 1,  4,  9, 16, 25])
>>> a - 2
array([-1,  0,  1,  2,  3])
>>> a / 2
array([ 0.5,  1. ,  1.5,  2. ,  2.5])
#等等
Copy after login

Change dimension:

>>> a = np.array([[1,2,3,4,5],[6,7,8,9,0]],dtype=np.int32)
>>> a
array([[1, 2, 3, 4, 5],
       [6, 7, 8, 9, 0]])
>>> a.reshape((5,2))
array([[1, 2],
       [3, 4],
       [5, 6],
       [7, 8],
       [9, 0]])
Copy after login

Matrix conversion (It is essentially different from changing dimensions, please be careful):

>>> a = np.array([[1,2,3,4,5],[6,7,8,9,0]],dtype=np.int32)
>>> a
array([[1, 2, 3, 4, 5],
       [6, 7, 8, 9, 0]])
>>> a.transpose()
array([[1, 6],
       [2, 7],
       [3, 8],
       [4, 9],
       [5, 0]])
Copy after login

Disrupt (can only disrupt one dimension):

>>> a = np.array([[1,2],[3,4],[5,6],[7,8],[9,0]],dtype=np.int32)
>>> a
array([[1, 2],
       [3, 4],
       [5, 6],
       [7, 8],
       [9, 0]])
       
>>> np.random.shuffle(a)
>>> a
array([[9, 0],
       [1, 2],
       [7, 8],
       [5, 6],
       [3, 4]])
Copy after login

4. Slicing and indexing:

One-dimensional array:

>>> a = np.array(range(10))
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a[3]
3
>>> a[2:9:2]
array([2, 4, 6, 8])
Copy after login

Multi-dimensional array:

>>> a = np.array([[1,2,3,4,5],[6,7,8,9,0],[11,12,13,14,15]],dtype=np.int32)
>>> a
array([[ 1,  2,  3,  4,  5],
       [ 6,  7,  8,  9,  0],
       [11, 12, 13, 14, 15]])
       
>>> a[:, 1:4]
array([[ 2,  3,  4],
       [ 7,  8,  9],
       [12, 13, 14]])
Copy after login

Conditions Index:

>>> a = np.array([[1,2,3,4,5],[6,7,8,9,0],[11,12,13,14,15]],dtype=np.int32)
>>> a
array([[ 1,  2,  3,  4,  5],
       [ 6,  7,  8,  9,  0],
       [11, 12, 13, 14, 15]])
       
>>> a > 5
array([[False, False, False, False, False],
       [ True,  True,  True,  True, False],
       [ True,  True,  True,  True,  True]], dtype=bool)
>>> a[a>5]
array([ 6,  7,  8,  9, 11, 12, 13, 14, 15])
>>> a%3 == 0
Out[128]: 
array([[False, False,  True, False, False],
       [ True, False, False,  True,  True],
       [False,  True, False, False,  True]], dtype=bool)
>>> a[a%3 == 0]
array([ 3,  6,  9,  0, 12, 15])
Copy after login

5. Function (numpy core knowledge points)

Calculation function:

np.ceil(): 向上最接近的整数,参数是 number 或 array
np.floor(): 向下最接近的整数,参数是 number 或 array
np.rint(): 四舍五入,参数是 number 或 array
np.isnan(): 判断元素是否为 NaN(Not a Number),参数是 number 或 array
np.multiply(): 元素相乘,参数是 number 或 array
np.divide(): 元素相除,参数是 number 或 array
np.abs():元素的绝对值,参数是 number 或 array
np.where(condition, x, y): 三元运算符,x if condition else y
>>> a = np.random.randn(3,4)
>>> a
array([[ 0.37091654,  0.53809133, -0.99434523, -1.21496837],
       [ 0.00701986,  1.65776152,  0.41319601,  0.41356973],
       [-0.32922342,  1.07773886, -0.27273258,  0.29474435]])
>>> np.ceil(a)      
array([[ 1.,  1., -0., -1.],
       [ 1.,  2.,  1.,  1.],
       [-0.,  2., -0.,  1.]])
>>> np.where(a>0, 10, 0)
array([[10, 10,  0,  0],
       [10, 10, 10, 10],
       [ 0, 10,  0, 10]])
Copy after login

Statistical function

np.mean():所有元素的平均值
np.sum():所有元素的和,参数是 number 或 array
np.max():所有元素的最大值
np.min():所有元素的最小值,参数是 number 或 array
np.std():所有元素的标准差
np.var():所有元素的方差,参数是 number 或 array
np.argmax():最大值的下标索引值,
np.argmin():最小值的下标索引值,参数是 number 或 array
np.cumsum():返回一个一维数组,每个元素都是之前所有元素的累加和
np.cumprod():返回一个一维数组,每个元素都是之前所有元素的累乘积,参数是 number 或 array
>>> a = np.arange(12).reshape(3,4).transpose()
>>> a
array([[ 0,  4,  8],
       [ 1,  5,  9],
       [ 2,  6, 10],
       [ 3,  7, 11]])
>>> np.mean(a)
5.5
>>> np.sum(a)
66
>>> np.argmax(a)
11
>>> np.std(a)
3.4520525295346629
>>> np.cumsum(a)
array([ 0,  4, 12, 13, 18, 27, 29, 35, 45, 48, 55, 66], dtype=int32)
Copy after login

Judgment function:

np.any(): 至少有一个元素满足指定条件,返回True
np.all(): 所有的元素满足指定条件,返回True
>>> a = np.random.randn(2,3)
>>> a
array([[-0.65750548,  2.24801371, -0.26593284],
       [ 0.31447911, -1.0215645 , -0.4984958 ]])
>>> np.any(a>0)
True
>>> np.all(a>0)
False
Copy after login

Remove duplicates:

np.unique(): 去重
>>> a = np.array([[1,2,3],[2,3,4]])
>>> a
array([[1, 2, 3],
       [2, 3, 4]])
>>> np.unique(a)
array([1, 2, 3, 4])
Copy after login

The above is the detailed content of Summary of simple usage of python numpy. 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

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)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 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)

Do mysql need to pay Do mysql need to pay Apr 08, 2025 pm 05:36 PM

MySQL has a free community version and a paid enterprise version. The community version can be used and modified for free, but the support is limited and is suitable for applications with low stability requirements and strong technical capabilities. The Enterprise Edition provides comprehensive commercial support for applications that require a stable, reliable, high-performance database and willing to pay for support. Factors considered when choosing a version include application criticality, budgeting, and technical skills. There is no perfect option, only the most suitable option, and you need to choose carefully according to the specific situation.

How to use mysql after installation How to use mysql after installation Apr 08, 2025 am 11:48 AM

The article introduces the operation of MySQL database. First, you need to install a MySQL client, such as MySQLWorkbench or command line client. 1. Use the mysql-uroot-p command to connect to the server and log in with the root account password; 2. Use CREATEDATABASE to create a database, and USE select a database; 3. Use CREATETABLE to create a table, define fields and data types; 4. Use INSERTINTO to insert data, query data, update data by UPDATE, and delete data by DELETE. Only by mastering these steps, learning to deal with common problems and optimizing database performance can you use MySQL efficiently.

MySQL can't be installed after downloading MySQL can't be installed after downloading Apr 08, 2025 am 11:24 AM

The main reasons for MySQL installation failure are: 1. Permission issues, you need to run as an administrator or use the sudo command; 2. Dependencies are missing, and you need to install relevant development packages; 3. Port conflicts, you need to close the program that occupies port 3306 or modify the configuration file; 4. The installation package is corrupt, you need to download and verify the integrity; 5. The environment variable is incorrectly configured, and the environment variables must be correctly configured according to the operating system. Solve these problems and carefully check each step to successfully install MySQL.

MySQL download file is damaged and cannot be installed. Repair solution MySQL download file is damaged and cannot be installed. Repair solution Apr 08, 2025 am 11:21 AM

MySQL download file is corrupt, what should I do? Alas, if you download MySQL, you can encounter file corruption. It’s really not easy these days! This article will talk about how to solve this problem so that everyone can avoid detours. After reading it, you can not only repair the damaged MySQL installation package, but also have a deeper understanding of the download and installation process to avoid getting stuck in the future. Let’s first talk about why downloading files is damaged. There are many reasons for this. Network problems are the culprit. Interruption in the download process and instability in the network may lead to file corruption. There is also the problem with the download source itself. The server file itself is broken, and of course it is also broken when you download it. In addition, excessive "passionate" scanning of some antivirus software may also cause file corruption. Diagnostic problem: Determine if the file is really corrupt

How to optimize MySQL performance for high-load applications? How to optimize MySQL performance for high-load applications? Apr 08, 2025 pm 06:03 PM

MySQL database performance optimization guide In resource-intensive applications, MySQL database plays a crucial role and is responsible for managing massive transactions. However, as the scale of application expands, database performance bottlenecks often become a constraint. This article will explore a series of effective MySQL performance optimization strategies to ensure that your application remains efficient and responsive under high loads. We will combine actual cases to explain in-depth key technologies such as indexing, query optimization, database design and caching. 1. Database architecture design and optimized database architecture is the cornerstone of MySQL performance optimization. Here are some core principles: Selecting the right data type and selecting the smallest data type that meets the needs can not only save storage space, but also improve data processing speed.

Does mysql need the internet Does mysql need the internet Apr 08, 2025 pm 02:18 PM

MySQL can run without network connections for basic data storage and management. However, network connection is required for interaction with other systems, remote access, or using advanced features such as replication and clustering. Additionally, security measures (such as firewalls), performance optimization (choose the right network connection), and data backup are critical to connecting to the Internet.

Solutions to the service that cannot be started after MySQL installation Solutions to the service that cannot be started after MySQL installation Apr 08, 2025 am 11:18 AM

MySQL refused to start? Don’t panic, let’s check it out! Many friends found that the service could not be started after installing MySQL, and they were so anxious! Don’t worry, this article will take you to deal with it calmly and find out the mastermind behind it! After reading it, you can not only solve this problem, but also improve your understanding of MySQL services and your ideas for troubleshooting problems, and become a more powerful database administrator! The MySQL service failed to start, and there are many reasons, ranging from simple configuration errors to complex system problems. Let’s start with the most common aspects. Basic knowledge: A brief description of the service startup process MySQL service startup. Simply put, the operating system loads MySQL-related files and then starts the MySQL daemon. This involves configuration

How to optimize database performance after mysql installation How to optimize database performance after mysql installation Apr 08, 2025 am 11:36 AM

MySQL performance optimization needs to start from three aspects: installation configuration, indexing and query optimization, monitoring and tuning. 1. After installation, you need to adjust the my.cnf file according to the server configuration, such as the innodb_buffer_pool_size parameter, and close query_cache_size; 2. Create a suitable index to avoid excessive indexes, and optimize query statements, such as using the EXPLAIN command to analyze the execution plan; 3. Use MySQL's own monitoring tool (SHOWPROCESSLIST, SHOWSTATUS) to monitor the database health, and regularly back up and organize the database. Only by continuously optimizing these steps can the performance of MySQL database be improved.

See all articles