15.1 C
London
Friday, July 5, 2024
HomePandas in PythonDataFrame Functions in PythonHow to Add a Numpy Array to a Pandas DataFrame

How to Add a Numpy Array to a 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...

Occasionally you may want to add a NumPy array as a new column to a pandas DataFrame.

Fortunately you can easily do this using the following syntax:

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

This tutorial shows a couple examples of how to use this syntax in practice.

Example 1: Add NumPy Array as New Column in DataFrame

The following code shows how to create a pandas DataFrame to hold some stats for basketball players and append a NumPy array as a new column titled ‘blocks’:

import numpy as np
import pandas as pd

#create pandas DataFrame
df = pd.DataFrame({'points': [25, 12, 15, 14, 19, 23, 25, 29],
                   'assists': [5, 7, 7, 9, 12, 9, 9, 4],
                   'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]})

#create NumPy array for 'blocks'
blocks = np.array([2, 3, 1, 0, 2, 7, 8, 2])

#add 'blocks' array as new column in DataFrame
df['blocks'] = blocks.tolist()

#display the DataFrame
print(df)

   points  assists  rebounds  blocks
0      25        5        11       2
1      12        7         8       3
2      15        7        10       1
3      14        9         6       0
4      19       12         6       2
5      23        9         5       7
6      25        9         9       8
7      29        4        12       2

Note that the new DataFrame now has an extra column titled blocks.

Example 2: Add NumPy Matrix as New Columns in DataFrame

The following code shows how to create a pandas DataFrame to hold some stats for basketball players and append a NumPy array as a new column titled ‘blocks’:

import numpy as np
import pandas as pd

#create pandas DataFrame
df = pd.DataFrame({'points': [25, 12, 15, 14, 19, 23

#create NumPy matrix
mat = np.matrix([[2, 3],
                 [1, 0],
                 [2, 7],
                 [8, 2],
                 [3, 4],
                 [7, 7],
                 [7, 5],
                 [6, 3]])

#add NumPy matrix as new columns in DataFrame
df_new = pd.concat([df, pd.DataFrame(mat)], axis=1)

#display new DataFrame
print(df_new)

   points  assists  rebounds  0  1
0      25        5        11  2  3
1      12        7         8  1  0
2      15        7        10  2  7
3      14        9         6  8  2
4      19       12         6  3  4
5      23        9         5  7  7
6      25        9         9  7  5
7      29        4        12  6  3

Note that the names of the columns for the matrix that we added to the DataFrame are given default column names of 0 and 1.

We can easily rename these columns using the df.columns function:

#rename columns
df_new.columns = ['pts', 'ast', 'rebs', 'new1', 'new2']

#display DataFrame
print(df_new)

   pts  ast  rebs  new1  new2
0   25    5    11     2     3
1   12    7     8     1     0
2   15    7    10     2     7
3   14    9     6     8     2
4   19   12     6     3     4
5   23    9     5     7     7
6   25    9     9     7     5
7   29    4    12     6     3

Additional Resources

How to Stack Multiple Pandas DataFrames
How to Merge Two Pandas DataFrames on Index
How to Convert Pandas DataFrame to NumPy Array
How to Rename Columns in Pandas

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