I'm quite new to Python and Pandas so this might be an obvious question.
I have a dataframe with ages listed in it. I want to create a new field with an age banding. I can use the lambda statement to capture a single if / else statement but I want to use multiple if's e.g. if age < 18 then 'under 18' elif age < 40 then 'under 40' else '>40'
.
I don't think I can do this using lambda but am not sure how to do it in a different way. I have this code so far:
import pandas as pd
import numpy as n
d = {'Age' : pd.Series([36., 42., 6., 66., 38.]) }
df = pd.DataFrame(d)
df['Age_Group'] = df['Age'].map(lambda x: '<18' if x < 19 else '>18')
print(df)
The pandas DataFrame provides a nice querying ability.
What you are trying to do can be done simply with:
The querying here is a powerful tool of the dataframe and will allow you to manipulate the DataFrame as you need.
For more complex conditionals, you can specify multiple conditions by encapsulating each condition in parenthesis and separating them with a boolean operator ( eg. '&' or '|')
You can see this in work here for the second conditional statement for setting >18.
Edit:
You can read more about indexing of DataFrame and conditionals:
http://pandas.pydata.org/pandas-docs/dev/indexing.html#index-objects
Edit:
To see how it works:
Edit:
To see how to do this without the chaining [using EdChums approach].
You can also do a nested np.where()