NumPy Creating Arrays
NumPy arrays are the foundation of numerical computation in Python. Arrays allow you to store multiple values in a single variable and perform operations on them efficiently. This is particularly useful when handling data, such as temperature variations in historic places like Chennai (Tamil Nadu, India) or Delhi (India).
Key Topics
Creating 1D Arrays
1D arrays are the simplest form of arrays in NumPy. They are similar to Python lists but provide better performance and flexibility.
Example
# Creating a 1D array
import numpy as np
temperatures = np.array([32, 35, 30, 28, 33])
print("Temperatures:", temperatures)
Output
Explanation: The np.array()
function converts a Python list into a NumPy array. This array can now be used for efficient numerical computations.
Creating 2D Arrays
2D arrays are used to represent tabular data, such as rainfall statistics in cities like Thanjavur (Tamil Nadu, India) and Udaipur (Rajasthan, India).
Example
# Creating a 2D array
rainfall = np.array([[120, 150], [90, 110]])
print("Rainfall statistics:")
print(rainfall)
Output
[[120 150]
[ 90 110]]
Explanation: A 2D array is created by passing a list of lists to np.array()
. This allows you to handle rows and columns of data effectively.
Array Initialization Methods
NumPy provides methods to initialize arrays directly without defining all their values manually. These methods are particularly useful when working with datasets representing large-scale computations.
Example
# Using zeros and ones
zeros_array = np.zeros((2, 3))
ones_array = np.ones((3, 2))
print("Zeros Array:")
print(zeros_array)
print("\nOnes Array:")
print(ones_array)
Output
[[0. 0. 0.]
[0. 0. 0.]]
Ones Array:
[[1. 1.]
[1. 1.]
[1. 1.]]
Explanation: The np.zeros()
function creates an array filled with zeros, and np.ones()
creates an array filled with ones. The shape of the array is specified as a tuple (rows, columns).
Key Takeaways
- Versatility: NumPy supports 1D and 2D arrays for handling a wide range of data.
- Efficiency: Arrays are faster and more memory-efficient than Python lists.
- Array Initialization: Use built-in functions like
np.zeros
,np.ones
, andnp.full
for efficient array creation. - Real-World Applications: Represent data from historical cities like Chennai, Thanjavur, and Udaipur effectively with arrays.