You can convert any datasets to dataframe using the pandas module. To do that you will use the pandas.DataFrame() constructor. You can also convert the dataframe to numpy array in python. In this tutorial you will know how to do that through steps.
Steps to convert data Dataframe to NumPy Array in Python
In Python, you can convert a Pandas DataFrame to a NumPy array using the values
attribute of the DataFrame. Below are all the steps for that.
Step 1: Import Libraries
Make sure you have the necessary libraries installed and import them. Import them using the import statement.
import pandas as pd
import numpy as np
Step 2: Create a DataFrame
Create sample dataframe for implementing the example. You can convert the datasets to dataframe using the pd.DataFrame() function.
data = {'C1': [10, 20, 30],
'C2': [40, 50, 60],
'C3': [70, 80, 90]}
df = pd.DataFrame(data)
Step 3: Convert to NumPy Array
Use the values
attribute of the DataFrame to convert it to a NumPy array.
numpy_array = df.values
The resulting numpy_array
will be a 2D NumPy array containing the values from the DataFrame.
Below is the full code for converting the dataframe to numpy array.
import pandas as pd
import numpy as np
# Create a DataFrame
data = {'C1': [10, 20, 30],
'C2': [40, 50, 60],
'C3': [70, 80, 90]}
df = pd.DataFrame(data)
# Convert DataFrame to NumPy array
numpy_array = df.values
print(numpy_array)
Conclusion
The above examples works well when your dataframe contains numerical data. Do not use it if the data contains multiple datatypes as the numpy array can store elements of single data type only.Thus if you wants to convert the dataframe to numpy arrays then the above steps will do that.
Leave a Reply