w3resource

How to convert a Pandas DataFrame to a NumPy array and back?

NumPy: Interoperability Exercise-13 with Solution

Write a NumPy program to create a Pandas DataFrame, convert it to a NumPy array, and then convert it back to a DataFrame.

Sample Solution:

Python Code:

import numpy as np
import pandas as pd

# Create a Pandas DataFrame
data = {
    'A': [1, 2, 3, 4],
    'B': [5, 6, 7, 8],
    'C': [9, 10, 11, 12]
}
df = pd.DataFrame(data)

# Print the original DataFrame
print("Original DataFrame:")
print(df)
print("Type:",type(df))


# Convert the DataFrame to a NumPy array
array = df.to_numpy()


# Print the NumPy array
print("\nNumPy Array:")
print(array)
print("Type:",type(array))


# Convert the NumPy array back to a DataFrame
df_back = pd.DataFrame(array, columns=df.columns)

# Print the DataFrame converted back from the NumPy array
print("\nDataFrame from NumPy Array:")
print(df_back)
print("Type:",type(df_back))

Output:

Original DataFrame:
   A  B   C
0  1  5   9
1  2  6  10
2  3  7  11
3  4  8  12
Type: <class 'pandas.core.frame.DataFrame'>

NumPy Array:
[[ 1  5  9]
 [ 2  6 10]
 [ 3  7 11]
 [ 4  8 12]]
Type: <class 'numpy.ndarray'>

DataFrame from NumPy Array:
   A  B   C
0  1  5   9
1  2  6  10
2  3  7  11
3  4  8  12
Type: <class 'pandas.core.frame.DataFrame'>

Explanation:

  • Import NumPy and Pandas Libraries: Import the NumPy and Pandas libraries to work with arrays and DataFrames.
  • Create Pandas DataFrame: Define a Pandas DataFrame with some example data.
  • Convert DataFrame to NumPy Array: Use the to_numpy() method of the DataFrame to convert it into a NumPy array.
  • Convert NumPy Array Back to DataFrame: Use the pd.DataFrame() constructor to convert the NumPy array back into a DataFrame, ensuring the column names match the original DataFrame.
  • Print Original DataFrame: Output the original DataFrame to compare with the converted versions.
  • Print NumPy Array: Output the NumPy array to verify the conversion.
  • Print DataFrame from NumPy Array: Output the DataFrame converted back from the NumPy array to verify the conversion accuracy.

Python-Numpy Code Editor:

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

Previous: How to convert a NumPy array to a Pandas series and print it?
Next: How to save a NumPy array to a CSV File and verify contents?

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/numpy/convert-a-pandas-dataframe-to-a-numpy-array-and-back.php