How to Create 2D Array from Dataframe Column in Python
To create a 2D array from a dataframe column in Python, you can use the to_numpy() function along with the reshape() function.
The following example shows how to create a 2D array from a dataframe column in Python using the to_numpy() and reshape() functions.
Using to_numpy() & reshape() Function
We can use the to_numpy() and reshape() functions to create a 2D array from a dataframe column.
Suppose we have the following dataframe:
# Import pandas library
import pandas as pd
# Create dataframe
df = pd.DataFrame({
'Date': ['01-03-2023', '01-03-2023', '01-03-2023', '01-03-2023', '02-03-2023', '02-03-2023'],
'Product_Code': ['A-101', 'A-102', 'A-103', 'B-101', 'B-102', 'B-104'],
'Product_Name': ['Laptop', 'Mobile', 'Printer', 'Keyboard', 'Scanner', 'Mouse'],
'Price': [4500, 550, 250, 50, 350, 50],
'Status': [1, 1, 1, 0, 1, 1]
})
# Create 1D array
array_1d = df["Price"].to_numpy()
# Create 2D array
array_2d = array_1d.reshape(2, 3)
# Show 2D array
print(array_2d)
Output: 👇️
[[4500 550 250]
[ 50 350 50]]
In this example, we use the to_numpy() function to convert the “Price” column of the dataframe df to a 1D array array_1d.
We then use the reshape() function to reshape the 1D array into a 2D array array_2d. The output shows the 2D array created from the dataframe column.
Conclusion
We can use the to_numpy() function along with the reshape() function to create a 2D array from a dataframe column in Python.