Python Pandas Example | Convert Numpy Array to Pandas Dataframe

In this python pandas example, we will introduce you how to convert a numpy array to pandas dataframe.

Step 1: import libraries

import numpy as np 
import pandas as pd 

Step 2: create a numpy data

In this example code, we will use np.random.rand() to create a numpy data.

For example:

arr = np.random.rand(4, 4) 
print("Numpy array : ",arr ) 

Step 3: convert numpy array to dataframe

We will use pd.DataFrame() to convert.

For example:

df = pd.DataFrame(arr, columns =['A', 'B', 'C', 'D']) 
print("\nPandas DataFrame: ")
print(df)

Finally, we will get a pandas dataframe from a numpy array.

Run this code, we may get:

Numpy array :  [[0.93845309 0.89059495 0.51480681 0.06583541]
 [0.94972596 0.55147651 0.40720578 0.86422873]
 [0.53556404 0.7760867  0.80657461 0.37336038]
 [0.21177783 0.90187237 0.53926327 0.06067915]]
Pandas DataFrame:
       A         B         C         D
0  0.938453  0.890595  0.514807  0.065835
1  0.949726  0.551477  0.407206  0.864229
2  0.535564  0.776087  0.806575  0.373360
3  0.211778  0.901872  0.539263  0.060679