How to Create 2D Matrix from Dataframe in Python
To create a 2D matrix from a dataframe in Python, you can use the to_numpy() function.
The following example shows how to create a 2D matrix from a dataframe in Python using the to_numpy() function.
Using to_numpy() Function
We can use the to_numpy() function to create a 2D matrix from a dataframe.
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": [45, 85, 95], "B": [11, 12, 13], "C": [25, 26, 24]})
# Create 2D matrix
matrix_ = df.to_numpy()
# Show matrix
print(matrix_)
Output: 👇️
[[45 11 25]
[85 12 26]
[95 13 24]]
In this example, we use the to_numpy() function to convert the dataframe df to a 2D matrix matrix_.
The output shows the 2D matrix created from the dataframe using the to_numpy() function.
Conclusion
We can use the to_numpy() function to create a 2D matrix from a dataframe in Python.