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:

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

Previous: Convert Pandas DataFrame to NumPy array and print.
Next: Convert dictionary to NumPy array and print.

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://198.211.115.131/python-exercises/numpy/convert-numpy-array-to-pandas-dataframe-and-print.php