Home Backend Development Python Tutorial Methods to convert matrices into lists and other functions in Python's numpy library_python

Methods to convert matrices into lists and other functions in Python's numpy library_python

Apr 04, 2018 pm 04:27 PM
numpy python Convert

Below I will share with you a method for converting matrices into lists and other functions in Python's numpy library. It has a good reference value and I hope it will be helpful to everyone. Let’s take a look together

This article mainly introduces some functions in Python’s numpy library and makes a backup for easy search.

(1) Function to convert matrix to list: numpy.matrix.tolist()

Return list list

Examples

>>>

>>> x = np.matrix(np.arange(12).reshape((3,4))); x
matrix([[ 0, 1, 2, 3],
  [ 4, 5, 6, 7],
  [ 8, 9, 10, 11]])
>>> x.tolist()
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
Copy after login

(2) Convert the array Function to convert to list: numpy.ndarray.tolist()

#Notes: (The array can be reconstructed)

The array may be recreated, a=np. array(a.tolist()).

Examples

>>>

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

(3) numpy.mean() calculates the mean of a matrix or array:

Examples

> ;>>

>>> a = np.array([[1, 2], [3, 4]]) #对所有元素求均值
>>> np.mean(a)
2.5
>>> np.mean(a, axis=0) #对每一列求均值
array([ 2., 3.])
>>> np.mean(a, axis=1) #对每一行求均值
array([ 1.5, 3.5])
Copy after login

(4) numpy.std() calculates the standard deviation of a matrix or array:

Examples

##>>>

>>> a = np.array([[1, 2], [3, 4]]) #对所有元素求标准差 
>>> np.std(a)
1.1180339887498949
>>> np.std(a, axis=0) #对每一列求标准差
array([ 1., 1.])
>>> np.std(a, axis=1) #对每一行求标准差
array([ 0.5, 0.5])
Copy after login

(5) numpy.newaxis adds a dimension to the array:

Examples:

>>> a=np.array([[1,2,3],[4,5,6],[7,8,9]]) #先输入3行2列的数组a
>>> b=a[:,:2] 
>>> b.shape #当数组的行与列都大于1时,不需增加维度
(3, 2)
>>> c=a[:,2] 
>>> c.shape #可以看到,当数组只有一列时,缺少列的维度
(3,)
>>> c
array([3, 6, 9])
Copy after login

>>> d=a[:,2,np.newaxis] #np.newaxis实现增加列的维度
>>> d
array([[3],
  [6],
  [9]])
>>> d.shape  #d的维度成了3行1列(3,1)
(3, 1)
>>> e=a[:,2,None] #None与np.newaxis实现相同的功能
>>> e
array([[3],
  [6],
  [9]])
>>> e.shape
(3, 1)
Copy after login

(6) numpy.random.shuffle(index): Disrupt the order of the data set (array):

Examples:

>>> index = [i for i in range(10)] 
>>> index 
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 
>>> np.random.shuffle(index) 
>>> index 
[7, 9, 3, 0, 4, 1, 5, 2, 8, 6]
Copy after login

(7) Calculate a certain row or a certain number of two-dimensional array Maximum and minimum value of a column:

>>> import numpy as np 
>>> a = np.arange(15).reshape(5,3) #构造一个5行3列的二维数组 
>>> a 
array([[ 0, 1, 2], 
  [ 3, 4, 5], 
  [ 6, 7, 8], 
  [ 9, 10, 11], 
  [12, 13, 14]]) 
>>> b = a[:,0].min() ##取第0列的最小值,其他列同理 
>>> b 
0 
>>> c = a[0,:].max() ##取第0行的最大值,其他行同理 
>>> c 
2
Copy after login

(8) Add columns to the array: np.hstack ()

n = np.array(np.random.randn(4,2)) 
 
n 
Out[153]: 
array([[ 0.17234 , -0.01480043], 
  [-0.33356669, -1.33565616], 
  [-1.11680009, 0.64230761], 
  [-0.51233174, -0.10359941]]) 
 
l = np.array([1,2,3,4]) 
 
l 
Out[155]: array([1, 2, 3, 4]) 
 
l.shape 
Out[156]: (4,)
Copy after login

As you can see, n is two-dimensional and l is one-dimensional. If you call np.hstack( directly ) will give an error: the dimensions are different.

n = np.hstack((n,l)) 
ValueError: all the input arrays must have same number of dimensions
Copy after login

The solution is to change l into two-dimensional, you can use the method in (5):

n = np.hstack((n,l[:,np.newaxis])) ##注意:在使用np.hstack()时必须用()把变量括起来,因为它只接受一个变量 
 
n 
Out[161]: 
array([[ 0.17234 , -0.01480043, 1.  ], 
  [-0.33356669, -1.33565616, 2.  ], 
  [-1.11680009, 0.64230761, 3.  ], 
  [-0.51233174, -0.10359941, 4.  ]])
Copy after login

Let’s talk about how to add values ​​to an empty list by column:

n = np.array([[1,2,3,4,5,6],[11,22,33,44,55,66],[111,222,333,444,555,666]]) ##产生一个三行六列容易区分的数组 
 
n 
Out[166]: 
array([[ 1, 2, 3, 4, 5, 6], 
  [ 11, 22, 33, 44, 55, 66], 
  [111, 222, 333, 444, 555, 666]]) 
 
sample = [[]for i in range(3)] ##产生三行一列的空列表 
Out[172]: [[], [], []] 
for i in range(0,6,2): ##每间隔一列便添加到sample中 
 sample = np.hstack((sample,n[:,i,np.newaxis]))  
  
 
sample 
Out[170]: 
array([[ 1., 3., 5.], 
  [ 11., 33., 55.], 
  [ 111., 333., 555.]])
Copy after login

Continuously updating...

Related recommendations:


Python's numpy library

Python NumPy library installation and usage notes

The above is the detailed content of Methods to convert matrices into lists and other functions in Python's numpy library_python. 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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
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)

How to open xml format How to open xml format Apr 02, 2025 pm 09:00 PM

Use most text editors to open XML files; if you need a more intuitive tree display, you can use an XML editor, such as Oxygen XML Editor or XMLSpy; if you process XML data in a program, you need to use a programming language (such as Python) and XML libraries (such as xml.etree.ElementTree) to parse.

Is there any mobile app that can convert XML into PDF? Is there any mobile app that can convert XML into PDF? Apr 02, 2025 pm 08:54 PM

An application that converts XML directly to PDF cannot be found because they are two fundamentally different formats. XML is used to store data, while PDF is used to display documents. To complete the transformation, you can use programming languages ​​and libraries such as Python and ReportLab to parse XML data and generate PDF documents.

Is the conversion speed fast when converting XML to PDF on mobile phone? Is the conversion speed fast when converting XML to PDF on mobile phone? Apr 02, 2025 pm 10:09 PM

The speed of mobile XML to PDF depends on the following factors: the complexity of XML structure. Mobile hardware configuration conversion method (library, algorithm) code quality optimization methods (select efficient libraries, optimize algorithms, cache data, and utilize multi-threading). Overall, there is no absolute answer and it needs to be optimized according to the specific situation.

How to modify comment content in XML How to modify comment content in XML Apr 02, 2025 pm 06:15 PM

For small XML files, you can directly replace the annotation content with a text editor; for large files, it is recommended to use the XML parser to modify it to ensure efficiency and accuracy. Be careful when deleting XML comments, keeping comments usually helps code understanding and maintenance. Advanced tips provide Python sample code to modify comments using XML parser, but the specific implementation needs to be adjusted according to the XML library used. Pay attention to encoding issues when modifying XML files. It is recommended to use UTF-8 encoding and specify the encoding format.

Recommended XML formatting tool Recommended XML formatting tool Apr 02, 2025 pm 09:03 PM

XML formatting tools can type code according to rules to improve readability and understanding. When selecting a tool, pay attention to customization capabilities, handling of special circumstances, performance and ease of use. Commonly used tool types include online tools, IDE plug-ins, and command-line tools.

Is there a free XML to PDF tool for mobile phones? Is there a free XML to PDF tool for mobile phones? Apr 02, 2025 pm 09:12 PM

There is no simple and direct free XML to PDF tool on mobile. The required data visualization process involves complex data understanding and rendering, and most of the so-called "free" tools on the market have poor experience. It is recommended to use computer-side tools or use cloud services, or develop apps yourself to obtain more reliable conversion effects.

How to convert XML to PDF on your phone with high quality? How to convert XML to PDF on your phone with high quality? Apr 02, 2025 pm 09:48 PM

Convert XML to PDF with high quality on your mobile phone requires: parsing XML in the cloud and generating PDFs using a serverless computing platform. Choose efficient XML parser and PDF generation library. Handle errors correctly. Make full use of cloud computing power to avoid heavy tasks on your phone. Adjust complexity according to requirements, including processing complex XML structures, generating multi-page PDFs, and adding images. Print log information to help debug. Optimize performance, select efficient parsers and PDF libraries, and may use asynchronous programming or preprocessing XML data. Ensure good code quality and maintainability.

How to convert XML files to PDF on your phone? How to convert XML files to PDF on your phone? Apr 02, 2025 pm 10:12 PM

It is impossible to complete XML to PDF conversion directly on your phone with a single application. It is necessary to use cloud services, which can be achieved through two steps: 1. Convert XML to PDF in the cloud, 2. Access or download the converted PDF file on the mobile phone.

See all articles