How to 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 DataFrame
print(df)

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

#print class of DataFrame
type(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

Leave a Reply

Your email address will not be published.