To create a new column in pandas based on a condition in Python, you can use the apply
method along with a lambda function or the numpy where
function.
Consider the following example DataFrame:
main.py132 chars6 lines
Suppose you want to create a new column called "Category" based on the condition that people aged 30 or above are assigned a category of "Senior" and others are assigned a category of "Junior".
Using apply
and a lambda function:
main.py78 chars2 lines
Using numpy where
:
main.py83 chars4 lines
Both methods will produce the same result:
main.py122 chars6 lines
Note that in the lambda function, you can define any condition based on your requirements and assign the appropriate category value.
gistlibby LogSnag