w3resource

Convert NumPy array to Pandas DataFrame and print


NumPy: Interoperability Exercise-6 with Solution


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

Sample Solution:

Python Code:

import numpy as np
import pandas as pd

# Initialize a NumPy array
numpy_array = np.array([[1, 2, 3],
                        [4, 5, 6],
                        [7, 8, 9]])

print("Original NumPy array:",numpy_array)
print("Type:",type(numpy_array))


# Convert the NumPy array to a Pandas DataFrame
df = pd.DataFrame(numpy_array, columns=['Column1', 'Column2', 'Column3'])
print("\nNumPy array to a Pandas DataFrame:")
# Print the Pandas DataFrame
print(df)
print(type(df))

Output:

Original NumPy array: [[1 2 3]
 [4 5 6]
 [7 8 9]]
Type: <class 'numpy.ndarray'>

NumPy array to a Pandas DataFrame:
   Column1  Column2  Column3
0        1        2        3
1        4        5        6
2        7        8        9
<class 'pandas.core.frame.DataFrame'>

Explanation:

  • Importing libraries: We first import the numpy and pandas libraries for array and DataFrame manipulations.
  • Initializing a NumPy array: A NumPy array is initialized with some elements.
  • Converting to Pandas DataFrame: The NumPy array is converted to a Pandas DataFrame using pd.DataFrame(). Column names are also provided.
  • Printing the DataFrame: The resulting Pandas DataFrame is printed.

Python-Numpy Code Editor: