Convert NumPy array to Pandas DataFrame and print
6. Array to DataFrame Conversion
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.
For more Practice: Solve these Related Problems:
- Write a Numpy program to convert a multidimensional NumPy array into a Pandas DataFrame with custom row and column labels.
- Write a Numpy program to convert a structured NumPy array to a DataFrame and then perform type coercion on specific columns.
- Write a Numpy program to convert a NumPy array to a DataFrame and then pivot the DataFrame based on a computed index column.
- Write a Numpy program to convert a flattened NumPy array into a DataFrame by reshaping it into a matrix with inferred dimensions.
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.