search
Search
Unlock 100+ guides
search toc
close
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
Doc Search
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Shrink
Navigate to

# Adding new columns to a DataFrame in Pandas

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

To add new columns to a DataFrame in Pandas, use the DataFrame's `assign(~)` method.

# Adding a column of constants

Consider the following DataFrame:

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

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

``` df.assign(C=20)    A  B  C0  3  5  201  4  6  20 ```

Here, note the following:

• the column name is specified by the keyword argument (e.g. `C=`).

• the source `df` is left intact, and a new DataFrame is returned.

To add a new column in place (i.e. modify `df` directly rather than returning a new DataFrame):

``` df["C"] = 20df    A  B  C0  3  5  201  4  6  20 ```

# Adding a column using an array

Consider the following DataFrame:

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

To append a new column using an array:

``` df.assign(C=[7,8])    A  B  C0  3  5  71  4  6  8 ```

Note that the length of the new column must match up with that of the source DataFrame.

# Adding a column using a function

Consider the following DataFrame:

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

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

``` df.assign(C=lambda my_df: my_df["A"] + my_df["B"])    A  B  C0  3  5  81  4  6  10 ```

Note that, whenever possible, opt for column-arithmetics instead for performance:

``` df["C"] = df["A"] + df["B"]df A B C0 3 5 81 4 6 10 ```

Consider the following DataFrame:

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

To append multiple columns in one-go, just specify multiple keyword arguments:

``` df.assign(C=20, D=[10,20])    A  B  C   D0  3  5  20  101  4  6  20  20 ```

Notice how the column labels are specified using keyword arguments (`C` and `D`).

Edited by 0 others
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!