How to Create Columns Based on Row Values of Dataframe in Python

To create columns based on row values of a dataframe in Python, you can use the apply() function.

The following example shows how to create columns based on row values of a dataframe in Python using the apply() function.

Using apply() Function

We can use the apply() function to create columns based on row values.

Let’s see how to use the apply() function in Python:

# Import pandas library
import pandas as pd

# Create dataframe 
df = 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]
})

# Define a function to create the status description
def status_desc(row):
    if row['Status'] == 1:
        return 'Available'
    else:
        return 'Out of Stock'

# Apply the function to create the new column
df['Status_Desc'] = df.apply(status_desc, axis=1)

# Show updated dataframe
print(df)

Output: 👇️

         Date Product_Code Product_Name  Price  Status   Status_Desc
0  01-03-2023        A-101       Laptop   4500       1     Available
1  01-03-2023        A-102       Mobile    550       1     Available
2  01-03-2023        A-103      Printer    250       1     Available
3  01-03-2023        B-101     Keyboard     50       0  Out of Stock
4  02-03-2023        B-102      Scanner    350       1     Available
5  02-03-2023        B-104        Mouse     50       1     Available

In this example, we use the apply() function to create a new column Status_Desc based on the values in the Status column of the dataframe df.

The output shows the updated dataframe with the new column added.

Conclusion

We can use the apply() function to create columns based on row values of a dataframe in Python.