Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (17.6k points)

To filter a dataframe (df) by a single column, if we consider data with male and females we might:

males = df[df[Gender]=='Male']

Question 1 - But what if the data spanned multiple years and i wanted to only see males for 2014?

In other languages I might do something like:

if A = "Male" and if B = "2014" then 

(except I want to do this and get a subset of the original dataframe in a new dataframe object)

Question 2. How do I do this in a loop, and create a dataframe object for each unique sets of year and gender (i.e. a df for: 2013-Male, 2013-Female, 2014-Male, and 2014-Female

for y in year:

for g in gender:

df = .....

1 Answer

0 votes
by (41.4k points)

Using & operator:

males = df[(df[Gender]=='Male') & (df[Year]==2014)]

Using a for loop to store your dataframes in a dict:

from collections import defaultdict

dic={}

for g in ['male', 'female']:

  dic[g]=defaultdict(dict)

  for y in [2013, 2014]:

    dic[g][y]=df[(df[Gender]==g) & (df[Year]==y)] #store the DataFrames to a dict of dict

Browse Categories

...