π Introduction
Creating arrays is the first practical step when working with NumPy.
NumPy provides multiple powerful functions to generate arrays quickly and efficiently.
π’ Why Use NumPy Array Creation Functions?
Instead of manually writing data, NumPy allows you to:
- Generate large datasets instantly
- Create structured arrays
- Save time in data processing
π§ͺ 1. Creating Array using array()
This is the most basic method.
import numpy as nparr = np.array([1, 2, 3, 4])
print(arr)
π 2. Using arange()
Works like Pythonβs range() but returns a NumPy array.
import numpy as nparr = np.arange(0, 10, 2)
print(arr)
π Output:
[0 2 4 6 8]
β Syntax:
np.arange(start, stop, step)
π 3. Using linspace()
Generates evenly spaced numbers between a range.
import numpy as nparr = np.linspace(0, 1, 5)
print(arr)
π Output:
[0. 0.25 0.5 0.75 1. ]
β Syntax:
np.linspace(start, stop, number_of_values)
βͺ 4. Using zeros()
Creates an array filled with zeros.
import numpy as nparr = np.zeros((2, 3))
print(arr)
π Output:
[[0. 0. 0.]
[0. 0. 0.]]
β« 5. Using ones()
Creates an array filled with ones.
import numpy as nparr = np.ones((2, 3))
print(arr)
π Output:
[[1. 1. 1.]
[1. 1. 1.]]
π’ Bonus: eye() (Identity Matrix)
import numpy as nparr = np.eye(3)
print(arr)
π Output:
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
π Comparison Table
| Function | Purpose |
|---|---|
| array() | Create from list |
| arange() | Range with step |
| linspace() | Equal spacing |
| zeros() | Fill with 0 |
| ones() | Fill with 1 |
| eye() | Identity matrix |
π§ Pro Tips
- Use
arange()for step-based sequences - Use
linspace()for precise spacing - Use
zeros()&ones()for initialization
π Works with Other Libraries
These arrays are used directly in:
- Pandas
- Matplotlib
- TensorFlow
π Conclusion
Mastering array creation in NumPy will make your data handling faster and more efficient.