How can I convert a NumPy array to a Pandas DataFrame?

Converting a NumPy array to a Pandas DataFrame is a simple process that can be done using the “pd.DataFrame()” function. This function takes in the NumPy array as its input and returns a Pandas DataFrame. By doing this, the data in the NumPy array can be easily organized and manipulated using the various functionalities of Pandas. This conversion allows for the use of Pandas’ powerful data analysis tools and makes it easier to work with structured, tabular data. It is a useful technique for data scientists, researchers, and analysts who need to perform data analysis and manipulation tasks on NumPy arrays.

Convert a NumPy Array to Pandas DataFrame


You can use the following syntax to convert a NumPy array into a pandas DataFrame:

#create NumPy array
data = np.array([[1, 7, 6, 5, 6], [4, 4, 4, 3, 1]])

#convert NumPy array to pandas DataFrame
df = pd.DataFrame(data=data)

The following example shows how to use this syntax in practice.

Example: Convert NumPy Array to Pandas DataFrame

Suppose we have the following NumPy array:

import numpy as np

#create NumPy array
data = np.array([[1, 7, 6, 5, 6], [4, 4, 4, 3, 1]])

#print class of NumPy array
type(data)

numpy.ndarray

We can use the following syntax to convert the NumPy array into a pandas DataFrame:

import pandas as pd

#convert NumPy array to pandas DataFrame
df = pd.DataFrame(data=data)

#print DataFrameprint(df)

   0  1  2  3  4
0  1  7  6  5  6
1  4  4  4  3  1

#print class of DataFrametype(df)
pandas.core.frame.DataFrame

Specify Row & Column Names for Pandas DataFrame

We can also specify row names and column names for the DataFrame by using the index and columns arguments, respectively.

#convert array to DataFrame and specify rows & columns
df = pd.DataFrame(data=data, index=["r1", "r2"], columns=["A", "B", "C", "D", "E"])

#print the DataFrame
print(df)

    A  B  C  D  E
r1  1  7  6  5  6
r2  4  4  4  3  1

Additional Resources

How to Add a Numpy Array to a Pandas DataFrame
How to Drop the Index Column in Pandas
Pandas: Select Rows Where Value Appears in Any Column

x