How to Add Numpy Arrays to a Pandas DataFrame

You can add a NumPy array as a new column to Pandas dataframes by using the tolist() function. The following are the syntax statement as well as examples showing how to actually do it.

df['new_column_name'] = array_name.tolist()

Step 1: Generate a sample dataframe

The following is to generate a dataframe and then print it out.

# generate a sample dataframe
car_data = {'Brand': ['Tesla', 'Tesla','Tesla','Ford'], 
     'Location': ['CA', 'CA','NY','MA'],
   Brand Location  Year
0  Tesla       CA  2019
1  Tesla       CA  2018
2  Tesla       NY  2020
3   Ford       MA  2019

Step 2: Generate a sample array using Numpy

The following is to generate an array using NumPy.

# generate a sample array using Numpy
import numpy as np
[88 33 44 55]

Step 3: Add the array into dataframe

The following Python code adds the array from Numpy into the dataframe.

# adding array from Numpy into a dataframe

The following is the updated dataframe after adding the array from NumPy.

   Brand Location  Year  Random_number
0  Tesla       CA  2019             88
1  Tesla       CA  2018             33
2  Tesla       NY  2020             44
3   Ford       MA  2019             55

Further Reading