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
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: