Store numpy.array() in cells of a Pandas.DataFrame()

Learn, how to store numpy.array() in cells of a Pandas.DataFrame() in Python?
Submitted by Pranit Sharma, on February 13, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Problem statement

Suppose that we are given a numpy array and a pandas dataframe and we need to store this numpy array in the cell of the pandas dataframe.

When we try to store the NumPy array in the cell of the pandas dataframe, the dataframe unpacks the elements of the numpy array. We need to find a way so that the dataframe store the numpy array as it is.

Storing numpy.array() in cells of a Pandas.DataFrame()

To store numpy.array() in cells, we will use a wrapper around the numpy array i.e., we will pass the numpy array as a list.

Let us understand with the help of an example,

Python program to store numpy.array() in cells of a Pandas.DataFrame()

# Importing pandas package
import pandas as pd

# Import numpy
import numpy as np

# Creating a numpy array
arr = np.array([1,2,3,4,5])

# Creating a dataframe using numpy array
df = pd.DataFrame({'A':[arr]})

# Display the DataFrame
print("Original DataFrame:\n",df,"\n\n")

Output

The output of the above program is:

Example: Add value at specific iloc into new dataframe column in pandas

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.