Transform pandas DataFrame to NumPy Array in Python (Example Code)

In this Python tutorial you’ll learn how to transform a pandas DataFrame to a NumPy Array.

Setting up the Example

import pandas as pd                               # Import pandas library in Python
my_df = pd.DataFrame({'A':range(15, 10, - 1),    # Construct DataFrame in Python
                      'B':['c', 'x', 'a', 'g', 'g'],
                      'C':range(105, 100, - 1)})
print(my_df)                                     # Display DataFrame in console
#     A  B    C
# 0  15  c  105
# 1  14  x  104
# 2  13  a  103
# 3  12  g  102
# 4  11  g  101

Example: Convert pandas DataFrame to NumPy Array

import numpy as np                                # Load numpy
my_array = my_df.to_numpy()                      # Using to_numpy() function
print(my_array)                                  # Display array in console
# [[15 'c' 105]
#  [14 'x' 104]
#  [13 'a' 103]
#  [12 'g' 102]
#  [11 'g' 101]]

Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top