0

I have a data frame that has various columns, one of them being sex which has 3 different value types:

  • male
  • female
  • NaN

and the other is employment types:

  • employed
  • unemployed

How do I create a function that takes in two strings (representing the the column names of interest) e.g function(sex, employment) and say I want to assign values in the data frame whose sex column value is Male = 1, Female = 2, NaN/other = 5 f and for employment, employed = 10, unemployed = 5 - Then make the function return the total of the two values above?

e.g function('Male', 'employed')

output = 11

1 Answer 1

1

There could be hundreds of ways to do this and I am still learning. So

  1. Create a dictionary for mapping

d = {'male': 1, 'female': 2, nan: 5, 'employed': 10, 'unemployed': 5}

  1. Create new columns with map integer values

df['Sex_Value'] = df['Sex'].map(d)

df['Employement_Value'] = df['Employement'].map(d)

df['Total'] = df['Sex_Value'] + df['Employement_Value']

  1. there are multiple ways here too

df.query("Sex == 'male' & Employement == 'employed'")['Total']

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.