In this post we will look at two methods to convert a pandas dataframe to numpy array.
Method 1 – to_numpy()
Let’s read a dataset to illustrate it.
import pandas as pd url = "https://raw.githubusercontent.com/bprasad26/lwd/master/data/winequality-red.csv" df = pd.read_csv(url) df.head()
Now, to convert this dataframe to numpy array, we can use to_numpy() method in pandas.
np_df = df.to_numpy() print(np_df) print(type(np_df))
Method 2 – DataFrame.values –
Convert a dataframe to numpy array, you can also use the DataFrame.values. However, pandas suggest that you use to_numpy() method.
np_df = df.values print(np_df) print(type(np_df))