mardi 14 juillet 2020

Creating a new column based on condition on other columns

I am trying to create a column based on a condition in other columns.

There are 5 Individuals Age in a house. I need to count no of individuals in that house by different gender and Age-groups.

Code I have written is not working

from pandas import DataFrame

df1 = pd.DataFrame({'member':[1,2], 'M1':[20,35],'M2':[27,42], 'M3':[77,62],'M4':[20,0],'M5':[0,35],
                    'G1':['M','F'],'G2':['M','F'],'G3':['M','F'],'G4':['M',0],'G5':[0,'F']})

#CODE WRITTEN
df1['M_20_to_30'] = ((df1[df1.columns[1:5]] >= 20) & (df1[df1.columns[1:5]] <= 30) & (df1[df1.columns[6:10]] == "M")).sum(1)


# EXPECTED OUTPUT
df1 = pd.DataFrame({'member':[1,2], 'M1':[20,35],'M2':[27,42], 'M3':[77,62],'M4':[20,0],'M5':[0,35],
                    'G1':['M','F'],'G2':['M','F'],'G3':['M','F'],'G4':['M',0],'G5':[0,'F'],'M_20_to_30':[2,0]})

Aucun commentaire:

Enregistrer un commentaire