create a matrix in pandas in python

To create a matrix in pandas, we can use the DataFrame() method. We can pass the data to be stored in the matrix as a list of lists or a numpy array.

Here's an example code snippet:

main.py
import pandas as pd
import numpy as np

# create a matrix using a list of lists
matrix_data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
df = pd.DataFrame(matrix_data)

# create a matrix using a numpy array
matrix_data_np = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
df_np = pd.DataFrame(matrix_data_np)

print("Matrix using list of lists:\n",df)
print("\nMatrix using numpy array:\n",df_np)
384 chars
14 lines

The output will be:

main.py
Matrix using list of lists:
    0  1  2
0  1  2  3
1  4  5  6
2  7  8  9

Matrix using numpy array:
    0  1  2
0  1  2  3
1  4  5  6
2  7  8  9
145 chars
12 lines

gistlibby LogSnag