JIYIK CN >

Current Location:Home > Learning > PROGRAM > Python >

Pandas DataFrame Create New Column Based on Other Columns

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

DataFrame.apply()This tutorial will show you how we can create new columns in Pandas DataFrame based on the values ​​of other columns in the DataFrame by applying functions to each element of a column or using methods.

import pandas as pd

items_df = pd.DataFrame(
    {
        "Id": [302, 504, 708, 103, 343, 565],
        "Name": ["Watch", "Camera", "Phone", "Shoes", "Laptop", "Bed"],
        "Cost": [300, 400, 350, 100, 1000, 400],
        "Discount(%)": [10, 15, 5, 0, 2, 7],
    }
)

print(items_df)

Output:

    Id    Name  Cost  Discount(%)
0  302   Watch   300           10
1  504  Camera   400           15
2  708   Phone   350            5
3  103   Shoes   100            0
4  343  Laptop  1000            2
5  565     Bed   400            7

We will use the DataFrame shown in the code snippet above to demonstrate how to create new columns in a Pandas DataFrame based on the values ​​of other columns in the DataFrame.


Creating New Columns in Pandas DataFrame Based on Other Columns’ Values ​​Element-wise

import pandas as pd

items_df = pd.DataFrame(
    {
        "Id": [302, 504, 708, 103, 343, 565],
        "Name": ["Watch", "Camera", "Phone", "Shoes", "Laptop", "Bed"],
        "Actual Price": [300, 400, 350, 100, 1000, 400],
        "Discount(%)": [10, 15, 5, 0, 2, 7],
    }
)

print("Initial DataFrame:")
print(items_df, "\n")

items_df["Final Price"] = items_df["Actual Price"] - (
    (items_df["Discount(%)"] / 100) * items_df["Actual Price"]
)


print("DataFrame after addition of new column")
print(items_df, "\n")

Output:

Initial DataFrame:
    Id    Name  Actual Price  Discount(%)
0  302   Watch           300           10
1  504  Camera           400           15
2  708   Phone           350            5
3  103   Shoes           100            0
4  343  Laptop          1000            2
5  565     Bed           400            7 

DataFrame after addition of new column
    Id    Name  Actual Price  Discount(%)  Final Price
0  302   Watch           300           10        270.0
1  504  Camera           400           15        340.0
2  708   Phone           350            5        332.5
3  103   Shoes           100            0        100.0
4  343  Laptop          1000            2        980.0
5  565     Bed           400            7        372.0 

It calculates the final price of each product by subtracting the discount amount value from Actual Pricethe column of the DataFrame. It then assigns the final price values Series​​to the column items_dfof the DataFrame Final Price.


DataFrame.apply()Create a new column in Pandas DataFrame based on the values ​​of other columns using

import pandas as pd

items_df = pd.DataFrame(
    {
        "Id": [302, 504, 708, 103, 343, 565],
        "Name": ["Watch", "Camera", "Phone", "Shoes", "Laptop", "Bed"],
        "Actual_Price": [300, 400, 350, 100, 1000, 400],
        "Discount_Percentage": [10, 15, 5, 0, 2, 7],
    }
)

print("Initial DataFrame:")
print(items_df, "\n")

items_df["Final Price"] = items_df.apply(
    lambda row: row.Actual_Price - ((row.Discount_Percentage / 100) * row.Actual_Price),
    axis=1,
)

print("DataFrame after addition of new column")
print(items_df, "\n")

Output:

Initial DataFrame:
    Id    Name  Actual_Price  Discount_Percentage
0  302   Watch           300                   10
1  504  Camera           400                   15
2  708   Phone           350                    5
3  103   Shoes           100                    0
4  343  Laptop          1000                    2
5  565     Bed           400                    7 

DataFrame after addition of new column
    Id    Name  Actual_Price  Discount_Percentage  Final Price
0  302   Watch           300                   10        270.0
1  504  Camera           400                   15        340.0
2  708   Phone           350                    5        332.5
3  103   Shoes           100                    0        100.0
4  343  Laptop          1000                    2        980.0
5  565     Bed           400                    7        372.0 

It apply()applies the lambda function defined in the method to items_dfeach row of the DataFrame and finally assigns a series of results to the columns items_dfof the DataFrame Final Price.

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

Finding the installed version of Pandas

Publish Date:2025/04/12 Views:190 Category:Python

Pandas is one of the commonly used Python libraries for data analysis, and Pandas versions need to be updated regularly. Therefore, other Pandas requirements are incompatible. Let's look at ways to determine the Pandas version and dependenc

KeyError in Pandas

Publish Date:2025/04/12 Views:81 Category:Python

This tutorial explores the concept of KeyError in Pandas. What is Pandas KeyError? While working with Pandas, analysts may encounter multiple errors thrown by the code interpreter. These errors are wide ranging and can help us better invest

Grouping and Sorting in Pandas

Publish Date:2025/04/12 Views:90 Category:Python

This tutorial explored the concept of grouping data in a DataFrame and sorting it in Pandas. Grouping and Sorting DataFrame in Pandas As we know, Pandas is an advanced data analysis tool or package extension in Python. Most of the companies

Plotting Line Graph with Data Points in Pandas

Publish Date:2025/04/12 Views:65 Category:Python

Pandas is an open source data analysis library in Python. It provides many built-in methods to perform operations on numerical data. Data visualization is very popular nowadays and is used to quickly analyze data visually. We can visualize

Converting Timedelta to Int in Pandas

Publish Date:2025/04/12 Views:123 Category:Python

This tutorial will discuss converting a to a using dt the attribute in Pandas . timedelta int Use the Pandas dt attribute to timedelta convert int To timedelta convert to an integer value, we can use the property pandas of the library dt .

Pandas fill NaN values

Publish Date:2025/04/12 Views:93 Category:Python

This tutorial explains how we can use DataFrame.fillna() the method to fill NaN values ​​with specified values. We will use the following DataFrame in this article. import numpy as np import pandas as pd roll_no = [ 501 , 502 , 503 , 50

Pandas Convert String to Number

Publish Date:2025/04/12 Views:147 Category:Python

This tutorial explains how to pandas.to_numeric() convert string values ​​of a Pandas DataFrame into numeric type using the method. import pandas as pd items_df = pd . DataFrame( { "Id" : [ 302 , 504 , 708 , 103 , 343 , 565 ], "Name" :

How to Change the Data Type of a Column in Pandas

Publish Date:2025/04/12 Views:139 Category:Python

We will look at methods for changing the data type of columns in a Pandas Dataframe, as well as options like to_numaric , , as_type and infer_objects . We will also discuss how to to_numaric use downcasting the option in . to_numeric Method

Get the first row of Dataframe Pandas

Publish Date:2025/04/12 Views:78 Category:Python

This tutorial explains how to use the get_first_row pandas.DataFrame.iloc attribute and pandas.DataFrame.head() get_first_row method from a Pandas DataFrame. We will use the following DataFrame in the following example to explain how to get

Scan to Read All Tech Tutorials

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

Recommended

Tags

Scan the Code
Easier Access Tutorial