杰瑞科技汇

Python import numpy有什么用?

Of course! Here is a comprehensive guide to importing and using numpy in Python, from the basic syntax to essential concepts and examples.

Python import numpy有什么用?-图1
(图片来源网络,侵删)

The Basic Import Statement

The standard way to import numpy is with the alias np. This is a widely adopted convention in the Python data science community.

import numpy as np

Why use as np? It's a shorthand that makes your code cleaner and more readable. Instead of writing numpy.array(), you can write np.array(), which is much more concise.


Why Use NumPy? The Core Advantage

NumPy's primary advantage is its powerful N-dimensional array object, called ndarray. These arrays are:

  • Fast: NumPy operations are implemented in C and are much faster than pure Python loops.
  • Memory Efficient: They store data in a contiguous block of memory, which is more efficient than Python's lists.
  • Convenient: They provide a huge library of built-in functions for mathematical, statistical, and logical operations.

Let's see the difference with a simple example.

Python import numpy有什么用?-图2
(图片来源网络,侵删)

Example: Calculating the Square of Numbers

Pure Python (with a list):

# Create a list of numbers
numbers = [1, 2, 3, 4, 5]
# Use a list comprehension to square each number
squares = [n**2 for n in numbers]
print(f"Original list: {numbers}")
print(f"Squared list: {squares}")

NumPy (with an array):

import numpy as np
# Create a NumPy array from the list
numbers_np = np.array([1, 2, 3, 4, 5])
# Square the entire array with a single operation!
squares_np = numbers_np ** 2
print(f"Original array: {numbers_np}")
print(f"Squared array: {squares_np}")

Notice how NumPy performed the operation on the entire array at once. This is called vectorization and is a key feature that makes NumPy so powerful and fast.


Common Ways to Create NumPy Arrays

Here are the most frequent methods for creating arrays.

Python import numpy有什么用?-图3
(图片来源网络,侵删)

a) From a Python List

This is the most common way. np.array() converts a list into a NumPy array.

import numpy as np
# From a list
my_list = [10, 20, 30]
arr_from_list = np.array(my_list)
print(f"From list: {arr_from_list}")
# From a list of lists (creates a 2D array)
matrix = [[1, 2, 3], [4, 5, 6]]
arr_from_matrix = np.array(matrix)
print(f"\nFrom matrix:\n{arr_from_matrix}")

b) Using Built-in Functions

NumPy has functions to create arrays of specific shapes and contents.

# Create an array of zeros
zeros_arr = np.zeros(5)  # 1D array of 5 zeros
print(f"Zeros: {zeros_arr}")
# Create a 2D array (matrix) of zeros
zeros_matrix = np.zeros((3, 4)) # 3 rows, 4 columns
print(f"\nZeros matrix:\n{zeros_matrix}")
# Create an array of ones
ones_arr = np.ones(3)
print(f"\nOnes: {ones_arr}")
# Create an array with a range of numbers (like Python's range)
range_arr = np.arange(10) # 0 to 9
print(f"\nArange: {range_arr}")
# Create an array with evenly spaced numbers over an interval
linspace_arr = np.linspace(0, 1, 5) # 5 numbers from 0 to 1
print(f"\nLinspace: {linspace_arr}")
# Create an array with random numbers
random_arr = np.random.rand(3, 2) # 3x2 matrix of random floats between 0 and 1
print(f"\nRandom array:\n{random_arr}")

Essential NumPy Array Attributes

Once you have an array, you'll often want to know its properties. These attributes are accessed as methods on the array object.

  • .shape: A tuple of the array's dimensions (rows, columns, ...).
  • .ndim: The number of dimensions (axes).
  • .size: The total number of elements in the array.
  • .dtype: The data type of the elements (e.g., int32, float64).
import numpy as np
# Create a 2D array
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(f"Array:\n{arr}")
print(f"Shape: {arr.shape}")      # Output: (2, 3) -> 2 rows, 3 columns
print(f"Dimensions: {arr.ndim}")   # Output: 2
print(f"Size: {arr.size}")        # Output: 6 (2 * 3)
print(f"Data Type: {arr.dtype}")  # Output: int64 (or similar)

Basic Operations

NumPy allows you to perform operations on entire arrays without writing loops.

a) Arithmetic Operations

These are performed element-wise.

import numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([10, 20, 30, 40])
print(f"a: {a}")
print(f"b: {b}")
print(f"Addition: {a + b}")
print(f"Subtraction: {b - a}")
print(f"Multiplication: {a * b}")
print(f"Division: {b / a}")
print(f"Exponentiation: {a ** 2}")

b) Aggregation Functions

These functions reduce an array to a single value.

import numpy as np
arr = np.array([1, 5, 2, 8, 3])
print(f"Array: {arr}")
print(f"Sum: {np.sum(arr)}")
print(f"Mean: {np.mean(arr)}")
print(f"Standard Deviation: {np.std(arr)}")
print(f"Minimum: {np.min(arr)}")
print(f"Maximum: {np.max(arr)}")

c) Reshaping and Indexing

import numpy as np
# Create a 1D array
arr_1d = np.arange(12)
print(f"1D array: {arr_1d}")
# Reshape it into a 3x4 matrix
arr_2d = arr_1d.reshape(3, 4)
print(f"\nReshaped to 3x4:\n{arr_2d}")
# Indexing (works like Python lists, but for multiple dimensions)
# Get the element in the 2nd row, 3rd column (indexing is 0-based)
element = arr_2d[1, 2]
print(f"\nElement at [1, 2]: {element}") # Output: 6
# Slicing: Get the first two rows
first_two_rows = arr_2d[:2, :]
print(f"\nFirst two rows:\n{first_two_rows}")

How to Install NumPy

If you don't have NumPy installed, you can install it easily using pip.

Open your terminal or command prompt and run:

pip install numpy

If you are using a Jupyter Notebook or Google Colab, you can run the command in a cell by prefixing it with an exclamation mark :

!pip install numpy

Putting It All Together: A Mini-Project

Let's say we have the test scores of 5 students in 3 subjects. We want to find the average score for each student and the average score for each subject.

import numpy as np
# Data: 5 students, 3 subjects (Math, Science, English)
scores = np.array([
    [85, 90, 78],
    [92, 88, 95],
    [76, 85, 82],
    [88, 91, 89],
    [95, 87, 93]
])
print("Original Scores Matrix:")
print(scores)
# --- Task 1: Find the average score for each student ---
# We want to calculate the mean along axis 1 (rows)
student_averages = np.mean(scores, axis=1)
print("\nAverage score for each student:")
print(student_averages)
# --- Task 2: Find the average score for each subject ---
# We want to calculate the mean along axis 0 (columns)
subject_averages = np.mean(scores, axis=0)
print("\nAverage score for each subject:")
print(subject_averages)

This example showcases how NumPy can handle multi-dimensional data and perform complex calculations with simple, readable code.

分享:
扫描分享到社交APP
上一篇
下一篇