Pandas DataFrame | assign method
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 |
---|---|
A function that takes in the source DataFrame as the sole argument, and returns a Series. | |
A scalar, Series or array holding the values of the column to append. |
There is no limit as to how many columns we can append at one time.
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
A B0 3 51 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 C0 3 5 81 4 6 10
Using a scalar
To append a new column whose values are a single constant:
df.assign(C=20)
A B C0 3 5 201 4 6 20
For your reference, we show the same df
here again:
df
A B0 3 51 4 6
Using an array
To append a new column using an array:
df.assign(C=[7,8])
A B C0 3 5 71 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 D0 3 5 8 131 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 B0 3 51 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 B0 8 51 9 6