Coding Ref

What is insert() in Pandas?

What is insert() in Pandas?

The insert() function in Pandas is used to insert a new column or row into a dataframe at a specified location.

This is often used to add a new column or row of data to an existing dataframe, without modifying the existing data.

Insert a new column

Here's an example of using the insert() function in Pandas to insert a new column into a dataframe:

main.py
import pandas as pd

# create a sample dataframe
df = pd.DataFrame({"A": [1, 2, 3, 4, 5],
                   "B": [6, 7, 8, 9, 10]})

# insert a new column C at position 2
df.insert(loc=2, column="C", value=[11, 12, 13, 14, 15])

# display the result
print(df)

This will insert a new column named C into the dataframe at position 2 (i.e., after the A column and before the B column), and populate the new column with the values [11, 12, 13, 14, 15].

The output will be:

output
   A   B   C
0  1   6  11
1  2   7  12
2  3   8  13
3  4   9  14
4  5  10  15

Insert a new row

You can also use the insert() function to insert a new row into a dataframe.

For example:

main.py
# insert a new row at position 2
df.loc[2] = [16, 17, 18]

# display the result
print(df)

This will insert a new row at position 2 in the dataframe, and populate the new row with the values [16, 17, 18].

The output will be:

    A   B   C
0   1   6  11
1   2   7  12
2  16  17  18
3   4   9  14
4   5  10  15

Conclusion

The insert() function is useful for inserting new columns or rows into a dataframe at a specified position, without modifying the existing data.

You'll also like

Related tutorials curated for you

    How to add an empty column to a Pandas DataFrame

    How to use nunique() in Pandas

    How to select multiple columns in Pandas

    How to filter a Pandas DataFrame

    How to use astype() in Pandas

    What is nlargest() in Pandas?

    How to reset index in a Pandas DataFrame

    How to sort a series in Pandas

    How to round in Pandas

    How to groupby mean in Pnadas

    How to give multiple conditions in loc() in Pandas

    How to change the order of columns in Pandas