How to Convert a Dataframe to a Matrix in Python

To convert a dataframe to a matrix in Python, you can use the DataFrame() function from the pandas library along with the array() or matrix() function from the numpy library.

The following examples show how to convert a dataframe to a matrix using two different functions in Python.

Using array() Function

We can use the array() function to convert a dataframe to a matrix.

Suppose we have the following dataframe:

# Import pandas and numpy library
import pandas as pd
import numpy as np

# Create dataframe
df = pd.DataFrame({"A": [78, 85, 89], "B": [12, 23, 24], "C": [55, 56, 57]})

# Create matrix
matrix1 = np.array(df)

# Show matrix
print(matrix1)

Output: 👇️

[[78 12 55]
 [85 23 56]
 [89 24 57]]

In this example, we use the array() function to convert the dataframe df to a matrix matrix1.

The output shows the matrix created from the dataframe using the array() function.

Using matrix() Function

We can use the matrix() function to convert a dataframe to a matrix.

Suppose we have the following dataframe:

# Import pandas and numpy library
import pandas as pd
import numpy as np

# Create dataframe
df = pd.DataFrame({"A": [78, 85, 89], "B": [12, 23, 24], "C": [55, 56, 57]})

# Create matrix
matrix2 = np.matrix(df)

# Show matrix
print(matrix2)

Output: 👇️

[[78 12 55]
 [85 23 56]
 [89 24 57]]

In this example, we use the matrix() function to convert the dataframe df to a matrix matrix2.

The output shows the matrix created from the dataframe using the matrix() function.

Conclusion

We can use the array() and matrix() functions from the numpy library to convert a dataframe to a matrix in Python.