w3resource

Convert Pandas DataFrame to NumPy array and print


NumPy: Interoperability Exercise-5 with Solution


Write a NumPy program to convert a Pandas DataFrame to a NumPy array and print the array.

Sample Solution:

Python Code:

import numpy as np
import pandas as pd

# Initialize a Pandas DataFrame
data = {'A': [1, 2, 3, 4, 5],
        'B': [10, 20, 30, 40, 50],
        'C': [100, 200, 300, 400, 500]}
df = pd.DataFrame(data)

print("Original Pandas DataFrame:",df)
print("Type:",type(df))

# Convert the Pandas DataFrame to a NumPy array
numpy_array = df.to_numpy()
print("\nPandas DataFrame to a NumPy array:")
# Print the NumPy array
print(numpy_array)
print("Type:",type(numpy_array))

Output:

Original Pandas DataFrame:    A   B    C
0  1  10  100
1  2  20  200
2  3  30  300
3  4  40  400
4  5  50  500
Type: <class 'pandas.core.frame.DataFrame'>

Pandas DataFrame to a NumPy array:
[[  1  10 100]
 [  2  20 200]
 [  3  30 300]
 [  4  40 400]
 [  5  50 500]]
Type: <class 'numpy.ndarray'>

Explanation:

  • Importing libraries: We first import the numpy and pandas libraries for array and DataFrame manipulations.
  • Initializing a DataFrame: A Pandas DataFrame is initialized with some data.
  • Converting to NumPy array: The Pandas DataFrame is converted to a NumPy array using the to_numpy() method.
  • Printing the array: The resulting NumPy array is printed.

Python-Numpy Code Editor: