Thursday, December 26, 2024
Google search engine
HomeLanguagesConvert a NumPy array to Pandas dataframe with headers

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:

numpy-array-to-dataframe-1

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:

numpy-araay-to-dataframe-2

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:

numpy-array-to-dataframe-3

RELATED ARTICLES

Most Popular

Recent Comments