w3resource

Convert Pandas DataFrame to NumPy array and print


5. DataFrame to Array Conversion

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.

For more Practice: Solve these Related Problems:

  • Write a Numpy program to convert a Pandas DataFrame with missing values to a NumPy array and fill missing entries using interpolation.
  • Write a Numpy program to convert a DataFrame containing mixed data types to a NumPy array and then enforce a uniform dtype via conversion.
  • Write a Numpy program to convert a large Pandas DataFrame to a NumPy array while preserving index and column metadata in separate arrays.
  • Write a Numpy program to convert a Pandas DataFrame to a NumPy array and then reshape the array based on selected DataFrame columns.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous:Convert NumPy array to Python tuple and Print.
Next: Convert NumPy array to Pandas DataFrame and print.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.