Issue
i want to create a Var that is conditional on an observation being in a list and some other criteria, so i tried this
emp_list1 = ["Gov.Sector","Semi Gov.Sector"]
PF_deftag['emp_grp1'] = np.where(
(PF_deftag['Employement Sector'] in ['emp_list1'] )
& (PF_deftag['Monthly salary in hand'].astype(float) < 3000),
1,
0
)
but get an error
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
In this case, no worries as this works
PF_deftag['emp_grp1'] = np.where(
((PF_deftag['Employement Sector'] == "Gov.Sector") |
(PF_deftag['Employement Sector'] == "Semi Gov.Sector"))
& (PF_deftag['Monthly salary in hand'].astype(float) < 3000),
1,
0
)
but the next condition may have 6 or 7 components to the list?
thanks
Solution
import numpy as np
# List of employment sectors you're interested in
emp_list1 = ["Gov.Sector", "Semi Gov.Sector"]
# Check if each row's 'Employement Sector' is in the list and monthly
salary is less than 3000
PF_deftag['emp_grp1'] = np.where(
(PF_deftag['Employement Sector'].isin(emp_list1)) &
(PF_deftag['Monthly salary in hand'].astype(float) < 3000),
1,
0
)
Explanation:
Import NumPy: import numpy as np
- Import the NumPy library for numerical operations.
Define Employment Sectors: emp_list1 = ["Gov.Sector", "Semi Gov.Sector"]
- Create a list of employment sectors you want to consider.
Apply Conditions: PF_deftag['emp_grp1'] = np.where(...)
- Check if each row's 'Employement Sector' is in the specified list and if the monthly salary is less than 3000. Assign 1 if true, 0 if false, to a new column 'emp_grp1'.
And for additional lists, you can expand it like this:
emp_list1 = ["Gov.Sector", "Semi Gov.Sector"]
emp_list2 = ["SomeSector1", "SomeSector2"]
PF_deftag['emp_grp1'] = np.where(
(
(PF_deftag['Employement Sector'].isin(emp_list1) |
PF_deftag['Employement Sector'].isin(emp_list2))
) & (PF_deftag['Monthly salary in hand'].astype(float) < 3000),
1,
0
)
Answered By - The JaBo Team
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.