search
Search
Login
Unlock 100+ guides
menu
menu
web
search toc
close
Comments
Log in or sign up
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
What does this mean?
Why is this true?
Give me some examples!
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
icon_star
Doc Search
icon_star
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Navigate to

Pandas DataFrame | assign method

schedule Aug 12, 2023
Last updated
local_offer
PythonPandas
Tags
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!

Pandas DataFrame.assign(~) method appends a new column to the DataFrame.

Parameters

1. kwargs | key:label and value:function or array-like

The key serves as the new column label.

Value Type

Description

functionlink

A function that takes in the source DataFrame as the sole argument, and returns a Series.

array-likelink

A scalar, Series or array holding the values of the column to append.

NOTE

You can reference previous columns that you've appended in the same call. Check the examples below for clarification.

Return value

A new DataFrame with the new columns appended.

Examples

Consider the following DataFrame:

df = pd.DataFrame({"A":[3,4], "B":[5,6]})
df
   A  B
0  3  5
1  4  6

Using a function

To append a new column C, which is the sum of column A and B:

df.assign(C=lambda my_df: my_df["A"] + my_df["B"])
   A  B  C
0  3  5  8
1  4  6  10

Using a scalar

To append a new column whose values are a single constant:

df.assign(C=20)
   A  B  C
0  3  5  20
1  4  6  20

For your reference, we show the same df here again:

df
A B
0 3 5
1 4 6

Using an array

To append a new column using an array:

df.assign(C=[7,8])
   A  B  C
0  3  5  7
1  4  6  8

Adding multiple columns

To add multiple columns in one-go:

df.assign(C=lambda p_df: p_df["A"] + p_df["B"], D=lambda p_df: p_df["C"] + 5)
   A  B  C  D
0  3  5  8  13
1  4  6  10 15

Notice how column D is constructed using column C, which also appears in the function call.

Overwriting an existing column

Consider the same DataFrame as before:

df
A B
0 3 5
1 4 6

If the label of the column you wish to append clashes with that of an existing column, then an overwrite will happen:

df.assign(A=[8,9])
A B
0 8 5
1 9 6
robocat
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...
thumb_up
0
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!