NumPy eye() Function
numpy.eye() is used to create a 2-D array (matrix) with 1s on the diagonal and 0s everywhere else.
Parameters
| Parameter | Meaning |
|---|---|
| N | Number of rows |
| M | Number of columns. If omitted, M = N |
| k | Diagonal position |
| dtype | Data type of the array |
1. Basic Example
Output:
This creates a 3 × 3 identity matrix.
2. dtype
By default, values are float.
Output:
3. Different Rows and Columns
Output:
Here:N = 3 → rowsM = 5 → columns
So the result is 3 × 5.
4. Important: k Parameter
k controls which diagonal gets the 1s.
- k = 0 → Main diagonal
- k = 1 → Above the main diagonal
- k = -1 → Below the main diagonal
k = -2
↓
k = -1
↓
0 1 0 0 0
1 0 1 0 0 ← k = 0 is this main diagonal
0 1 0 1 0
0 0 1 0 1
0 0 0 1 0
↑
k = +1
In short:
eye() is particularly useful when teaching identity matrices, diagonal matrices, linear algebra, and matrix operations in NumPy.
NumPy identity() Function
np.identity() creates a square identity matrix — a matrix having 1 on the main diagonal and 0 everywhere else.
1. Basic Example
Output:
Here 3 means 3 rows × 3 columns.
2. Using dtype
By default, the values are float.
Output:
identity() vs eye()
Important point:
| Feature | np.identity() |
np.eye() |
|---|---|---|
| Square matrix | ✅ Always | ❌ Not necessarily |
| Rows | n |
N |
| Columns | n |
M (optional) |
| Main diagonal | 1 |
1 |
| k parameter | ❌ No | ✅ Yes |
Example
Always gives:
Whereas:
can create:
And:
can move the diagonal:
identity() = square identity matrix onlyeye() = more flexible identity/diagonal matrixnp.identity(5) is essentially a convenient way to create a 5 × 5 identity matrix.
NumPy diag() Function
np.diag() is used for two different purposes:
- Create a diagonal matrix from a 1-D array/list.
- Extract the diagonal from a 2-D matrix.
1. Create a diagonal matrix
Output:
The values become the main diagonal.
2. Extract diagonal from a matrix
Output:
So:
3. k parameter
k specifies which diagonal to use.
- Main diagonal — k=0
- Above main diagonal — k=1
- Below main diagonal — k=-1
diag() vs eye() vs identity()
| Function | Purpose |
|---|---|
np.identity(3) |
3×3 identity matrix |
np.eye(3) |
Identity-like matrix, more flexible |
np.diag([10,20,30]) |
Create diagonal matrix with 10,20,30 |
np.diag(matrix) |
Extract diagonal from matrix |
np.identity(3)→ Only1s on diagonalnp.eye(3, k=1)→1s on selected diagonalnp.diag([10,20,30])→ Your values on diagonalnp.diag(matrix)→ Get diagonal values from matrix
NumPy fromfunction() and fromfile()
Both functions are used to create NumPy arrays, but their purposes are different.
np.fromfunction()creates an array by applying a function to array indices.np.fromfile()creates an array by reading data from a text or binary file.
1. NumPy fromfunction()
The np.fromfunction() function creates an array by executing a function on the indices of each element.
| Parameter | Description |
|---|---|
| function | Function used to generate values |
| shape | Dimensions of the output array |
| dtype | Data type of the coordinate arrays passed to the function |
Example 1: Create a 1-D array
Output:
Explanation:
| Index (i) | Formula (i*2) | Result |
|---|---|---|
| 0 | 0 × 2 | 0 |
| 1 | 1 × 2 | 2 |
| 2 | 2 × 2 | 4 |
| 3 | 3 × 2 | 6 |
| 4 | 4 × 2 | 8 |
The function receives the indices, not existing array values.
Example 2: Create a 2-D array
Output:
How does it work?
irepresents the row index.jrepresents the column index.(3,4)creates three rows and four columns.- Each element is calculated using
i+j.
For example:
Example 3: Multiplication table
Output:
This creates a multiplication table without explicitly writing a Python loop.
Example 4: Create even and odd patterns
Output:
This is useful for generating a checkerboard pattern.
Example 5: Using a normal function instead of lambda
Output:
fromfunction() normally calls the supplied function once with coordinate arrays. It does not call the Python function separately for every element.
2. NumPy fromfile()
The np.fromfile() function reads data from an existing file and converts it into a NumPy array.
It supports two formats:
- Text files
- Binary files
| Parameter | Description | Default |
|---|---|---|
| file | File name or file object | Required |
| dtype | Data type | float |
| count | Number of elements to read | -1 (all) |
| sep | Separator between text values | '' (binary mode) |
Example 1: Read numbers from a text file
Suppose we have a file named numbers.txt.
File content:
Python:
Output:
sep=" " tells NumPy to read whitespace-separated text values. Without sep, NumPy uses binary mode.
Example 2: Read comma-separated values
File: marks.txt
Python:
Output:
Example 3: Using count
File: numbers.txt
Python:
Output:
Only four elements are read.
Example 4: Convert file data into a 2-D array
File: data.txt
Python:
Output:
Notice that fromfile() returns a 1-D array. To convert it into a matrix:
Output:
Example 5: Write and read binary data
First, create a binary file:
Now read the file:
Output:
np.save() and np.load() are generally preferable because they preserve array shape and dtype information.
3. Difference Between fromfunction() and fromfile()
| Feature | fromfunction() |
fromfile() |
|---|---|---|
| Purpose | Generate array using function | Read array from file |
| Existing file required | No | Yes |
| Lambda supported | Yes | Not applicable |
| Shape parameter | Yes | No |
| Supports multidimensional output | Yes | Returns 1-D |
| Main use | Mathematical patterns | File data loading |
| Input | Function and shape | File path |
4. Practice Questions ✍️
fromfunction()
- Create a 1-D array containing squares of numbers from 0 to 9.
- Create a 4×4 matrix where each element is
i+j. - Create a 5×5 multiplication table.
- Create a 3×3 matrix containing
i*i+j*j. - Create a 5×5 matrix with 1 at even row-column index sums and 0 elsewhere.
fromfile()
- Create a text file containing 10 integers and read them into a NumPy array.
- Read only the first five values from a file.
- Read comma-separated marks from a text file.
- Read nine numbers from a file and reshape them into a 3×3 matrix.
- Save a NumPy array to a binary file using
tofile()and read it usingfromfile().