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 | insert 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.insert(~) method inserts a new column into the source DataFrame.

WARNING

The insertion is done in-place, that is, the source DataFrame is directly modified and no new DataFrame is created.

Parameters

1. loclink | int

The integer index of the location to insert.

2. columnlink | string

The label of the column you want to insert into.

3. valuelink | int or array-like

The column data. If a single scalar is given, then the value will be repeated to fit the number of columns in the source DataFrame.

4. allow_duplicateslink | boolean | optional

Whether or not to allow columns with duplicate column labels. If False, then an error will be raised whenever duplicate column labels are inserted. By default, allow_duplicates=False.

Return Value

None as the insertion is performed in-place.

Examples

Consider the following DataFrame:

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

Inserting using a list

To insert a new column C:

df.insert(2, "C", [8,9])
df
A B C
0 4 6 8
1 5 7 9

Inserting using a scalar

To insert a new column C with a repeated constant:

df.insert(2, "C", 8)
df
A B C
0 4 6 8
1 5 7 8

Notice how the value 8, which is a scalar, has been repeated to fill up the column.

Allowing duplicate column labels

By default, when you try to add a column with a column label that already exists in the source DataFrame, an error will be raised:

df.insert(2, "B", 8)
df
ValueError: cannot insert B, already exists

You can still allow for duplicate column labels by setting allow_duplicates=True:

df.insert(2, "B", 8, allow_duplicates=True)
df
A B B
0 4 6 8
1 5 7 8
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!