Home »
Python »
Python Programs
Add NumPy array as column to Pandas dataframe
Learn, how to add NumPy array as column to Pandas dataframe?
Submitted by Pranit Sharma, on January 08, 2023
NumPy is an abbreviated form of Numerical Python. It is used for different types of scientific operations in python. Numpy is a vast library in python which is used for almost every kind of scientific or mathematical operation. It is itself an array which is a collection of various methods and functions for processing the arrays.
Adding NumPy array as column to Pandas dataframe
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.
We have a method in NumPy called toarray() which we will use to convert the NumPy array into an array that will be added to the dataframe as a new column.
Let us understand with the help of an example,
Python code to add NumPy array as column to Pandas dataframe
# Import numpy
import numpy as np
# Import pandas
import pandas as pd
# Import sparse
import scipy.sparse as sparse
# Creating a dataframe
df = pd.DataFrame(np.arange(1,10).reshape(3,3))
# Display original dataframe
print("Original DataFrame:\n",df,"\n")
# Creating a matrix and then adding it as a column in df
arr = sparse.coo_matrix(([1,1,1], ([0,1,2], [1,2,0])), shape=(3,3))
df['New'] = arr.toarray().tolist()
# Display new df
print("New Dataframe:\n",df,"\n")
Output:
Python NumPy Programs »