简体   繁体   English

根据其他列的条件创建新列

[英]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.一个房子里有5个人年龄。 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]})

You could do:你可以这样做:

df1['M_20_to_30'] = (df1
                     .iloc[:,df1.columns.str.startswith('M')]
                     .apply(lambda x: sum(x.ge(20) & x.le(30))), 1))

   member  M1  M2  M3  M4  M5 G1 G2 G3 G4 G5  M_20_to_30
0       1  20  27  77  20   0  M  M  M  M  0           3
1       2  35  42  62   0  35  F  F  F  0  F           0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM