How to Create Array From Dataframe Column in Python
To create an array from a dataframe column in Python, you can use the to_numpy() function.
The following example shows how to create an array from a dataframe column in Python using the to_numpy() function.
Using to_numpy() Function
We can use the to_numpy() function to create an array from a dataframe column.
Suppose we have the following dataframe:
# Import library
import pandas as pd
import numpy as np
# Create a 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 array from column
arr = df['Product_Name'].to_numpy()
# Show array
print(arr)
Output: 👇️
['Laptop' 'Mobile' 'Printer' 'Keyboard' 'Scanner' 'Mouse']
In this example, we use the to_numpy() function to create an array arr from the Product_Name column of the dataframe df.
The output shows the array created from the dataframe column.
Conclusion
We can use the to_numpy() function to create an array from a dataframe column in Python.