JIYIK CN >

Current Location:Home > Learning > PROGRAM > Python >

Pandas Insert Method in Python

Author:JIYIK Last Updated:2025/04/30 Views:

This tutorial explains how to insert()insert a column in a Pandas DataFrame using the method.

import pandas as pd

countries_df = pd.DataFrame(
    {
        "Country": ["Nepal", "Switzerland", "Germany", "Canada"],
        "Continent": ["Asia", "Europe", "Europe", "North America"],
        "Primary Language": ["Nepali", "French", "German", "English"],
    }
)
print("Countries DataFrame:")
print(countries_df, "\n")

Output:

Countries DataFrame:
       Country      Continent Primary Language
0        Nepal           Asia           Nepali
1  Switzerland         Europe           French
2      Germany         Europe           German
3       Canada  North America          English

We will use the DataFrame shown in the above example countries_dfto explain how to insert()insert a column in a Pandas DataFrame using the method.


pandas.DataFrame.insert()method

grammar

DataFrame.insert(loc, column, value, allow_duplicates=False)

It columninserts a column named DataFrameinto , with the value valuespecified by , at locposition .

Use insert()the method to insert a column with the same value for all rows

import pandas as pd

countries_df = pd.DataFrame(
    {
        "Country": ["Nepal", "Switzerland", "Germany", "Canada"],
        "Continent": ["Asia", "Europe", "Europe", "North America"],
        "Primary Language": ["Nepali", "French", "German", "English"],
    }
)
print("Countries DataFrame:")
print(countries_df, "\n")

countries_df.insert(3, "Capital", "Unknown")

print("Countries DataFrame after inserting Capital column:")
print(countries_df)

Output:

Countries DataFrame:
       Country      Continent Primary Language
0        Nepal           Asia           Nepali
1  Switzerland         Europe           French
2      Germany         Europe           German
3       Canada  North America          English

Countries DataFrame after inserting Capital column:
       Country      Continent Primary Language  Capital
0        Nepal           Asia           Nepali  Unknown
1  Switzerland         Europe           French  Unknown
2      Germany         Europe           German  Unknown
3       Canada  North America          English  Unknown

It inserts the Capital column at index in countries_dfthe DataFrame 3, with the Capital column value set to for all rows Unknown.

The position 0starts at , so 3the position refers to the column in the DataFrame 4.

Insert a column into a DataFrame, specifying the value for each row

If we want insert()to specify the values ​​for the columns to be inserted into each row using the method, we can insert()pass a list of values ​​as valuethe parameter in the method.

import pandas as pd

countries_df = pd.DataFrame(
    {
        "Country": ["Nepal", "Switzerland", "Germany", "Canada"],
        "Continent": ["Asia", "Europe", "Europe", "North America"],
        "Primary Language": ["Nepali", "French", "German", "English"],
    }
)
print("Countries DataFrame:")
print(countries_df, "\n")

capitals = ["Kathmandu", "Zurich", "Berlin", "Ottawa"]

countries_df.insert(2, "Capital", capitals)

print("Countries DataFrame after inserting Capital column:")
print(countries_df)

Output:

Countries DataFrame:
       Country      Continent Primary Language
0        Nepal           Asia           Nepali
1  Switzerland         Europe           French
2      Germany         Europe           German
3       Canada  North America          English

Countries DataFrame after inserting Capital column:
       Country      Continent    Capital Primary Language
0        Nepal           Asia  Kathmandu           Nepali
1  Switzerland         Europe     Zurich           French
2      Germany         Europe     Berlin           German
3       Canada  North America     Ottawa          English

It inserts the column countries_dfat index in the DataFrame and assigns the value of each row to the column in the DataFrame .2CapitalCapital


Set in insert()the method allow_duplicates = Trueto add an existing column

import pandas as pd

countries_df = pd.DataFrame(
    {
        "Country": ["Nepal", "Switzerland", "Germany", "Canada"],
        "Continent": ["Asia", "Europe", "Europe", "North America"],
        "Primary Language": ["Nepali", "French", "German", "English"],
        "Capital": ["Kathmandu", "Zurich", "Berlin", "Ottawa"],
    }
)
print("Countries DataFrame:")
print(countries_df, "\n")

capitals = ["Kathmandu", "Zurich", "Berlin", "Ottawa"]

countries_df.insert(4, "Capital", capitals, allow_duplicates=True)

print("Countries DataFrame after inserting Capital column:")
print(countries_df)

Output:

Countries DataFrame:
       Country      Continent Primary Language    Capital
0        Nepal           Asia           Nepali  Kathmandu
1  Switzerland         Europe           French     Zurich
2      Germany         Europe           German     Berlin
3       Canada  North America          English     Ottawa

Countries DataFrame after inserting Capital column:
       Country      Continent Primary Language    Capital    Capital
0        Nepal           Asia           Nepali  Kathmandu  Kathmandu
1  Switzerland         Europe           French     Zurich     Zurich
2      Germany         Europe           German     Berlin     Berlin
3       Canada  North America          English     Ottawa     Ottawa

It Capitaladds the column to countries_dfthe DataFrame, even though the column countries_dfalready exists in the DataFrame Capital.

If we try to insert a column that already exists in the DataFrame without insert()setting it in the method allow_duplicates = True, it will throw us an error message: ValueError: cannot insert column, already exists..

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Pandas DataFrame DataFrame.query() function

Publish Date:2025/04/30 Views:107 Category:Python

The pandas.DataFrame.query() method filters the rows of the caller DataFrame using the given query expression. pandas.DataFrame.query() grammar DataFrame . query(expr, inplace = False , ** kwargs) parameter expr Filter rows based on query e

Pandas DataFrame DataFrame.min() function

Publish Date:2025/04/30 Views:162 Category:Python

Python Pandas DataFrame.min() function gets the minimum value of the DataFrame object along the specified axis. pandas.DataFrame.min() grammar DataFrame . mean(axis = None , skipna = None , level = None , numeric_only = None , ** kwargs) pa

Pandas DataFrame DataFrame.mean() function

Publish Date:2025/04/30 Views:85 Category:Python

Python Pandas DataFrame.mean() function calculates the mean of the values ​​of the DataFrame object over the specified axis. pandas.DataFrame.mean() grammar DataFrame . mean(axis = None , skipna = None , level = None , numeric_only = No

Pandas DataFrame DataFrame.isin() function

Publish Date:2025/04/30 Views:133 Category:Python

The pandas.DataFrame.isin(values) function checks whether each element in the caller DataFrame contains values the value specified in the input . pandas.DataFrame.isin(values) grammar DataFrame . isin(values) parameter values iterable - lis

Pandas DataFrame DataFrame.groupby() function

Publish Date:2025/04/30 Views:161 Category:Python

pandas.DataFrame.groupby() takes a DataFrame as input and divides the DataFrame into groups based on a given criterion. We can use groupby() the method to easily process large datasets. pandas.DataFrame.groupby() grammar DataFrame . groupby

Pandas DataFrame DataFrame.fillna() function

Publish Date:2025/04/30 Views:60 Category:Python

The pandas.DataFrame.fillna() function replaces the values DataFrame ​​in NaN with a certain value. pandas.DataFrame.fillna() grammar DataFrame . fillna( value = None , method = None , axis = None , inplace = False , limit = None , down

Pandas DataFrame DataFrame.dropna() function

Publish Date:2025/04/30 Views:181 Category:Python

The pandas.DataFrame.dropna() function removes null values ​​(missing values) from a DataFrame by dropping rows or columns that contain null values DataFrame . NaN ( Not a Number ) and NaT ( Not a Time ) represent null values. DataFrame

Pandas DataFrame DataFrame.assign() function

Publish Date:2025/04/30 Views:55 Category:Python

Python Pandas DataFrame.assign() function assigns new columns to DataFrame . pandas.DataFrame.assign() grammar DataFrame . assign( ** kwargs) parameter **kwargs Keyword arguments, DataFrame the column names to be assigned to are passed as k

Pandas DataFrame DataFrame.transform() function

Publish Date:2025/04/30 Views:120 Category:Python

Python Pandas DataFrame.transform() DataFrame applies a function on and transforms DataFrame . The function to be applied is passed as an argument to the function. The axis length of transform() the transformed should be the same as the ori

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial