In this post we will see how to convert Convert Pandas DataFrame to NumPy Array.
Table of Contents
You can use DataFrame.to_numpy()
to convert Pandas DataFrame to NumPy Array.
Syntax of DataFrame.to_numpy()
1 2 3 |
Dataframe.to_numpy(dtype = None, copy = False) |
Parameters
dtype: Data type for target numpy array.
copy: [bool, default False] Whether to ensure that the returned value is a not a view on another array.
Return
DataFrame.to_numpy() returns NumPy.ndArray.
Example 1: Convert Pandas DataFrame to NumPy Array
Here is simple example to convert Pandas DataFrame to NumPy Array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import pandas as pd #Create a dataframe df = pd.DataFrame( [[32, 89, 47,87], [67, 68, 69,78], [87, 92, 56,98], [98, 45, 76,99]], columns=['C1', 'C2', 'C3','C4']) print(' Original DataFrame\n----------\n', df) #convert dataframe to numpy array nArray = df.to_numpy() print('-----Numpy Array-----\n',nArray) |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
Original DataFrame ---------- C1 C2 C3 C4 0 32 89 47 87 1 67 68 69 78 2 87 92 56 98 3 98 45 76 99 -----Numpy Array----- [[32 89 47 87] [67 68 69 78] [87 92 56 98] [98 45 76 99]] |
Example 2: Convert Pandas DataFrame to NumPy Array with mix dtypes
If you have dataframe with mixed dtypes, then NumPy array will be created of lowest dataTypes.
For example:
Python DataFrame with int64
qnd float64
will be convert to NumPy array of type float64
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import pandas as pd #Create a dataframe df = pd.DataFrame( [[32, 89.3, 47,87], [67, 68.2, 69,78], [87, 92.4, 56,98], [98, 45.03, 76,99]], columns=['C1', 'C2', 'C3','C4']) print(' Original DataFrame\n----------\n', df) #convert pandas dataframe to numpy array nArray = df.to_numpy() print('-----Numpy Array-----\n',nArray) |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
Original DataFrame ---------- C1 C2 C3 C4 0 32 89.30 47 87 1 67 68.20 69 78 2 87 92.40 56 98 3 98 45.03 76 99 -----Numpy Array----- [[32. 89.3 47. 87. ] [67. 68.2 69. 78. ] [87. 92.4 56. 98. ] [98. 45.03 76. 99. ]] |
That’s all about How to convert Pandas DataFrame to NumPy Array