4.5 C
London
Friday, December 20, 2024
HomePandas in PythonGeneral Functions in PythonHow to Convert a NumPy Array to Pandas DataFrame

How to Convert a NumPy Array to Pandas DataFrame

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories