>>> df = pd.DataFrame({"A": [1, 2], "B": [3.0, 4.5]}) >>> df.to_numpy() array([[1. , 3. ], [2. , 4.5]])
Here is what the above code is Doing:
1. We create a DataFrame with two columns, A and B.
2. We use the to_numpy() method to convert the DataFrame to a NumPy array.
3. We print the resulting array to the console.
As you can see, the to_numpy() method returns a NumPy array with the same data as the DataFrame.
The to_numpy() method is useful if you want to perform mathematical operations on your data. For example, you can use the NumPy mean() function to calculate the mean of each column:
>>> df = pd.DataFrame({“A”: [1, 2], “B”: [3.0, 4.5]})
>>> df.to_numpy().mean()
2.75
You can also use the NumPy std() function to calculate the standard deviation of each column:
>>> df = pd.DataFrame({“A”: [1, 2], “B”: [3.0, 4.5]})
>>> df.to_numpy().std()
1.2990381056766576
As you can see, the to_numpy() method is a powerful tool that you can use to perform mathematical operations on your data.
In the next tutorial, you’ll learn how to use the Pandas read_csv() function to read data from a CSV file.