Home Backend Development Python Tutorial Summary of commonly used functions in the Numpy library: a powerful tool for data analysis and modeling

Summary of commonly used functions in the Numpy library: a powerful tool for data analysis and modeling

Jan 19, 2024 am 09:10 AM
data analysis numpy Modeling

Summary of commonly used functions in the Numpy library: a powerful tool for data analysis and modeling

Numpy is one of the most commonly used mathematical libraries in Python, which integrates many of the best mathematical functions and operations. Numpy is widely used, including statistics, linear algebra, image processing, machine learning, neural networks and other fields. In terms of data analysis and modeling, Numpy is one of the indispensable tools. This article will share commonly used mathematical functions in Numpy, as well as sample codes for using these functions to implement data analysis and modeling.

1. Create an array

Use the array() function in Numpy to create an array. Code example:

import numpy as np

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

This will output [1 2 3 4 5], indicating that a one-dimensional array is created.

We can also create a two-dimensional array, code example:

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)
Copy after login

This will output:

[[1 2 3]
 [4 5 6]]
Copy after login

means that a two-dimensional array is created.

2. Array attributes

Use the ndim, shape and size attributes in Numpy to obtain the dimensions of the array. Shape and number of elements, code example:

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr.ndim)  # 输出 2,表示数组是二维的
print(arr.shape)  # 输出 (2, 3),表示数组有2行3列
print(arr.size)  # 输出 6,表示数组有6个元素
Copy after login

3. Array operations

Numpy arrays can perform operations such as addition, subtraction, multiplication, and division. First, let’s look at the operation of adding a scalar to an array. Code example:

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
print(arr + 2)  # 输出 [3 4 5 6 7]
Copy after login

means that 2 is added to each element in the array.

The next step is the operation of adding two arrays. Code example:

import numpy as np

arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
print(arr1 + arr2)  # 输出 [5 7 9]
Copy after login

means adding the corresponding elements in the two arrays.

Numpy also provides some specific operations, such as:

  • Square operation: use the power() function, code example:

    import numpy as np
    
    arr = np.array([1, 2, 3, 4, 5])
    print(np.power(arr, 2))  # 输出 [ 1  4  9 16 25]
    Copy after login

    This means that each element in the array is squared.

  • Square root operation: use the sqrt() function, code example:

    import numpy as np
    
    arr = np.array([1, 4, 9, 16, 25])
    print(np.sqrt(arr))  # 输出 [1. 2. 3. 4. 5.]
    Copy after login

    This means that each element in the array has the square root .

  • Sum: Use the sum() function, code example:

    import numpy as np
    
    arr = np.array([1, 2, 3, 4, 5])
    print(np.sum(arr))  # 输出 15
    Copy after login

    This means summing all elements in the array.

  • Find the maximum and minimum values: use the max() and min() functions, code example:

    import numpy as np
    
    arr = np.array([1, 2, 3, 4, 5])
    print(np.max(arr))  # 输出 5,表示数组中的最大值
    print(np.min(arr))  # 输出 1,表示数组中的最小值
    Copy after login

4. Array indexing and slicing

We can use subscripts to access elements in the array, code example:

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
print(arr[0])  # 输出 1,表示数组中的第一个元素
Copy after login

We can also perform slicing operations on the array , Code example:

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
print(arr[1:4])  # 输出 [2 3 4],表示从数组中取出第2个到第4个元素
Copy after login

5. Transformation of array shape

Numpy provides some functions for changing the shape of the array, one of which is the reshape() function . We can use the reshape() function to reshape the array, code example:

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
print(arr.reshape(5, 1))
Copy after login

This will return a two-dimensional array with shape (5, 1):

[[1]
 [2]
 [3]
 [4]
 [5]]
Copy after login

6. Merging and splitting arrays

Numpy provides some functions for merging and splitting arrays.

We can use the concatenate() function to merge two arrays along a certain dimension, code example:

import numpy as np

arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
print(np.concatenate((arr1, arr2)))  # 输出 [1 2 3 4 5 6]
Copy after login

We can also use vstack() The and hstack() functions stack two arrays together horizontally or vertically, code example:

import numpy as np

arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])

# 垂直堆叠
print(np.vstack((arr1, arr2)))  # 输出 [[1 2 3] [4 5 6]]

# 水平堆叠
print(np.hstack((arr1, arr2)))  # 输出 [1 2 3 4 5 6]
Copy after login

We can also use the split() function to Split an array into multiple arrays, code example:

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
print(np.split(arr, 5))  # 输出 [array([1]), array([2]), array([3]), array([4]), array([5])]
Copy after login

This will split the array into 5 one-dimensional arrays, each containing only one element.

7. Comprehensive Example

Now, we will use functions in Numpy to implement a simple data analysis and modeling example.

Example: Suppose you have the scores of 100 students and you want to calculate their average score, highest score, and lowest score.

First, we use the random() function to generate 100 random numbers, and use mean(), max() and ## The #min() function calculates their average, highest and lowest values, code example:

import numpy as np

grades = np.random.randint(50, 100, 100)  # 生成50到100之间的100个随机数
print("平均成绩:", np.mean(grades))
print("最高成绩:", np.max(grades))
print("最低成绩:", np.min(grades))
Copy after login

Next, we will use the

histogram() function to generate a score Histogram, code example:

import matplotlib.pyplot as plt
import numpy as np

grades = np.random.randint(50, 100, 100)  # 生成50到100之间的100个随机数
hist, bins = np.histogram(grades, bins=10, range=(50, 100))

plt.hist(grades, bins=10, range=(50, 100))
plt.show()
Copy after login

Finally, we will use the

percentile() function to calculate the percentile of the score, code example:

import numpy as np

grades = np.random.randint(50, 100, 100)  # 生成50到100之间的100个随机数
print("90%的成绩高于:", np.percentile(grades, 90))
Copy after login
The above is the summary of this article Common Numpy functions, these functions can help us achieve data analysis and modeling. Hope these sample codes can help readers understand better.

The above is the detailed content of Summary of commonly used functions in the Numpy library: a powerful tool for data analysis and modeling. 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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months 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)

Upgrading numpy versions: a detailed and easy-to-follow guide Upgrading numpy versions: a detailed and easy-to-follow guide Feb 25, 2024 pm 11:39 PM

How to upgrade numpy version: Easy-to-follow tutorial, requires concrete code examples Introduction: NumPy is an important Python library used for scientific computing. It provides a powerful multidimensional array object and a series of related functions that can be used to perform efficient numerical operations. As new versions are released, newer features and bug fixes are constantly available to us. This article will describe how to upgrade your installed NumPy library to get the latest features and resolve known issues. Step 1: Check the current NumPy version at the beginning

Step-by-step guide on how to install NumPy in PyCharm and get the most out of its features Step-by-step guide on how to install NumPy in PyCharm and get the most out of its features Feb 18, 2024 pm 06:38 PM

Teach you step by step to install NumPy in PyCharm and make full use of its powerful functions. Preface: NumPy is one of the basic libraries for scientific computing in Python. It provides high-performance multi-dimensional array objects and various functions required to perform basic operations on arrays. function. It is an important part of most data science and machine learning projects. This article will introduce you to how to install NumPy in PyCharm, and demonstrate its powerful features through specific code examples. Step 1: Install PyCharm First, we

Uncover the secret method to quickly uninstall the NumPy library Uncover the secret method to quickly uninstall the NumPy library Jan 26, 2024 am 08:32 AM

The secret of how to quickly uninstall the NumPy library is revealed. Specific code examples are required. NumPy is a powerful Python scientific computing library that is widely used in fields such as data analysis, scientific computing, and machine learning. However, sometimes we may need to uninstall the NumPy library, whether to update the version or for other reasons. This article will introduce some methods to quickly uninstall the NumPy library and provide specific code examples. Method 1: Use pip to uninstall pip is a Python package management tool that can be used to install, upgrade and

In-depth analysis of numpy slicing operations and application in actual combat In-depth analysis of numpy slicing operations and application in actual combat Jan 26, 2024 am 08:52 AM

Detailed explanation of numpy slicing operation method and practical application guide Introduction: Numpy is one of the most popular scientific computing libraries in Python, providing powerful array operation functions. Among them, slicing operation is one of the commonly used and powerful functions in numpy. This article will introduce the slicing operation method in numpy in detail, and demonstrate the specific use of slicing operation through practical application guide. 1. Introduction to numpy slicing operation method Numpy slicing operation refers to obtaining a subset of an array by specifying an index interval. Its basic form is:

Numpy installation guide: Solving installation problems in one article Numpy installation guide: Solving installation problems in one article Feb 21, 2024 pm 08:15 PM

Numpy installation guide: One article to solve installation problems, need specific code examples Introduction: Numpy is a powerful scientific computing library in Python. It provides efficient multi-dimensional array objects and tools for operating array data. However, for beginners, installing Numpy may cause some confusion. This article will provide you with a Numpy installation guide to help you quickly solve installation problems. 1. Install the Python environment: Before installing Numpy, you first need to make sure that Py is installed.

Conversion between Tensor and Numpy: Examples and Applications Conversion between Tensor and Numpy: Examples and Applications Jan 26, 2024 am 11:03 AM

Examples and applications of Tensor and Numpy conversion TensorFlow is a very popular deep learning framework, and Numpy is the core library for Python scientific computing. Since both TensorFlow and Numpy use multi-dimensional arrays to manipulate data, in practical applications, we often need to convert between the two. This article will introduce how to convert between TensorFlow and Numpy through specific code examples, and explain its use in practical applications. head

Guide to uninstalling the NumPy library to avoid conflicts and errors Guide to uninstalling the NumPy library to avoid conflicts and errors Jan 26, 2024 am 10:22 AM

The NumPy library is one of the important libraries in Python for scientific computing and data analysis. However, sometimes we may need to uninstall the NumPy library, perhaps because we need to upgrade the version or resolve conflicts with other libraries. This article will introduce readers to how to correctly uninstall the NumPy library to avoid possible conflicts and errors, and demonstrate the operation process through specific code examples. Before we start uninstalling the NumPy library, we need to make sure that the pip tool is installed, because pip is the package management tool for Python.

How to model your own model in Kujiale - Steps in modeling your own model in Kujiale How to model your own model in Kujiale - Steps in modeling your own model in Kujiale Mar 04, 2024 pm 07:55 PM

Many users who have just come into contact with the Kujiale software are not very familiar with how Kujiale models themselves? The following article brings you the steps of Kujiale's own modeling. Let's take a look. Enter the Kujiale platform. In Kujiale, click to enter the design and decoration interface. In the design interface, click on the industry library on the left, and click on the whole house hardware installation tools in the industry library. In the whole house hard decoration tool, modeling operations can be performed.

See all articles