NumPy ndarray & Array Creation Methods
Python tutorial · PySpark.in
What is ndarray?
An ndarray (N-dimensional array) is a fundamental data structure in NumPy that stores elements of the same data type in a multi-dimensional, fixed-size array, enabling fast and memory-efficient numerical computations.
Creating Arrays using array()
Syntax
```
Hide
np.array(object, dtype=None)
```
Example
```
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr)
```
1D, 2D, and 3D Arrays
1D Array
```
a = np.array([10, 20, 30])
print(a)
```
Used for: lists, vectors, simple data
2D Array
```
b = np.array([[1, 2], [3, 4]])
print(b)
```
Used for: matrices, tables, datasets
3D Array
```
c = np.array([
[[1, 2], [3, 4]],
[[5, 6], [7, 8]]
])
print(c)
```
Used for: images, videos, ML tensors
Array Attributes
ndim – Number of Dimensions
```
A=a.ndim
print(A)
```
Tells whether the array is 1D, 2D, or 3D.
shape – Structure of Array
```
B=b.shape
print(B)
```
Represents rows × columns.
size – Total Elements
```
B=b.size
print(B)
```
Total number of elements in the array.
Data Type of Array
dtype
```
X=arr.dtype
print(X)
```
Shows type of elements stored.
astype() – Type Conversion
```
arr_float = arr.astype(float)
print(arr_float)
```
Creates a new array with changed data type.
Memory Size of Array
itemsize
```
X=arr.itemsize
print(X)
```
Shows memory (in bytes) used by one element.
Array Creation Methods
NumPy provides built-in functions to create arrays efficiently without manual data entry.
1.zeros()
Creates an array filled with zeros.
```
P=np.zeros((3, 3))
print(P)
```
Used for initialization in ML & matrices.
2.ones()
Creates an array filled with ones.
```
K=np.ones((2, 2))
print(K)
```
Useful in normalization and bias initialization.
3.empty()
Creates an array without initializing values.
```
S=np.empty((2, 2))
print(S)
```
Faster but contains garbage values.
4.full()
Creates an array filled with a specific value.
```
Y=np.full((2, 3), 7)
print(Y)
```
Used when constant values are needed.
5.eye(){identity matrix}:Used in linear algebra & matrix operations.
```
X=np.eye(3)
print(X)
```
6.arange()
Creates array with a range of values.
```
X=np.arange(0, 10, 2)
print(X)
```
Similar to range() but returns NumPy array.
7.linspace()
Creates array with evenly spaced values.
8.np.linspace(0, 1, 5)
Used in graphs, ML scaling, statistics.
Practical Example (Combined)
```
import numpy as np
a = np.zeros((2,2))
b = np.ones((2,2))
c = np.eye(2)
d = np.arange(1, 10)
e = np.linspace(1, 5, 5)
print(a, b, c, d, e)
```
More Python tutorials
- What is Python and Why is it used for Data Science and Data Engineering?
- How Does Python Work in the Backend? Internal Working of Python
- Top 30 Python Interview Questions for Data Science
- 3-Month Python Roadmap to Excel in Data Science and Machine Learning
- Python Data Types Explained – A Beginner’s Guide
- test
All tutorials · Try the free PySpark compiler · Practice challenges