How to Create a Column Without Appending it to the Dataframe in Python

To create a new column without appending it to the dataframe, you first need to make a copy of the dataframe. This can be done using the copy() method in pandas.

Then, create the new column using the standard syntax for adding a new column to a dataframe, but instead of appending it to the original dataframe, we assign it to the new copy.

The following example shows how to create a column without appending it to the dataframe in Python using the copy() function.

Using copy() Function

We can use the copy() function to create a new column without appending it to the original dataframe.

Suppose we have the following dataframe:

# Import pandas library
import pandas as pd

# Create dataframe
office_stuff = pd.DataFrame({
    'Date': ['01-03-2023', '01-03-2023', '01-03-2023', '01-03-2023', '02-03-2023', '02-03-2023'],
    'Product_Code': ['A-101', 'A-102', 'A-103', 'B-101', 'B-102', 'B-104'],
    'Product_Name': ['Laptop', 'Mobile', 'Printer', 'Keyboard', 'Scanner', 'Mouse'],
    'Price': [4500, 550, 250, 50, 350, 50],
    'Status': [1, 1, 1, 0, 1, 1]
})

# Create a copy of the dataframe
office_copy = office_stuff.copy()

# Create a new column with a calculation
office_copy['Price_with_tax'] = office_copy['Price'] * 1.10

# Display the new dataframe with the new column
print(office_copy)

Output: 👇️

         Date Product_Code Product_Name  Price  Status  Price_with_tax
0  01-03-2023        A-101       Laptop   4500       1          4950.0
1  01-03-2023        A-102       Mobile    550       1           605.0
2  01-03-2023        A-103      Printer    250       1           275.0
3  01-03-2023        B-101     Keyboard     50       0            55.0
4  02-03-2023        B-102      Scanner    350       1           385.0
5  02-03-2023        B-104        Mouse     50       1            55.0

In this example, we created a new column called Price_with_tax that calculates the price with a 10% tax.

The copy() method creates a new copy of the original dataframe, and the new column is assigned to the copy using the standard syntax for adding a new column.

The original dataframe remains unchanged, and we now have a new dataframe with the calculated column.

Conclusion

We can use the copy() function to create a column without appending it to the original dataframe in Python.