Pandas DataFrame to NumPy Array

In this post we will see how to convert Convert Pandas DataFrame to NumPy Array.
[toc]
You can convert Pandas DataFrame to Numpy Array to perform mathematical computation supported by NumPy library.

You can use DataFrame.to_numpy() to convert Pandas DataFrame to NumPy Array.

Syntax of DataFrame.to_numpy()

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.

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

 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

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

 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

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.