Convert a NumPy array to Pandas dataframe with headers
To convert a numpy array to pandas dataframe, we use pandas.DataFrame() function of Python Pandas library.
Syntax: pandas.DataFrame(data=None, index=None, columns=None)
Parameters:
data: numpy ndarray, dict or dataframe
index: index for resulting dataframe
columns: column labels for resulting dataframe
Example 1 :
import numpy as np import pandas as pd arr = np.random.rand( 4 , 3 ) print ( "Numpy array:" ) print (arr) # convert numpy array to dataframe df = pd.DataFrame(arr, columns = [ 'A' , 'B' , 'C' ]) print ( "\nPandas DataFrame: " ) df |
Output:
Example 2 :
import numpy as np import pandas as pd arr = np.random.rand( 6 ).reshape( 2 , 3 ) print ( "Numpy array:" ) print (arr) # convert numpy array to dataframe df = pd.DataFrame(arr, columns = [ 'C1' , 'C2' , 'C3' ]) print ( "\nPandas DataFrame: " ) df |
Output:
Example 3 :
import numpy as np import pandas as pd arr = np.array([[ 1 , 2 ], [ 4 , 5 ]]) print ( "Numpy array:" ) print (arr) # convert numpy array to dataframe df = pd.DataFrame(data = arr, index = [ "row1" , "row2" ], columns = [ "col1" , "col2" ]) print ( "\nPandas DataFrame: " ) df |
Output:
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.