检查条件是否在两个值之间并分配虚拟变量

2024-04-18 02:22:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图检查某个租客是否在指定的年龄范围内,然后给它赋值一个二进制变量,不管它是不是

我尝试在列上使用lambda函数:

df['<= 18'] = df['rider_age'].apply(lambda x: 1 if x <= 18 else 0)
df['19-24'] = df['rider_age'].apply(lambda x: 1 if x <=19 & x >=24 else 0)
df['25-35'] = df['rider_age'].apply(lambda x: 1 if x <=25 & x >=35 else 0)
df['36-50'] = df['rider_age'].apply(lambda x: 1 if x <=36 & x >=50 else 0)
df['51-59'] = df['rider_age'].apply(lambda x: 1 if x <=51 & x >=59 else 0)
df['51-59'] = df['rider_age'].apply(lambda x: 1 if x <=51 & x >=59 else 0)
df['60+'] =   df['rider_age'].apply(lambda x: 1 if x >=60 else 0)

现在,这适用于18岁以下和60岁以上的人,但它只是将年龄介于0和0之间的人标记为1。你知道吗

有人知道怎么做吗?你知道吗


Tags: lambda函数标记dfageif二进制else
3条回答

你可以用cut+get_dummies检查

s=pd.cut(df['rider_age'],[-np.Inf,18,24,35,50,59,np.Inf]).astype(str).str.get_dummies()

然后concat返回

df=pd.concat([df,s], axis=1)

通过将条件从&;更改为和来修复代码

apply(lambda x: 1 if x <=19 and x >=24 else 0)

你把一些不等式搞混了。。。你知道吗

看看第二种情况:x必须是<;=19和>;=24。你一定是说>;=19和<;=24,对吧?你知道吗

我只修改你的代码。对于那些中间命令,您的条件是错误的。你需要=> & <=而不是<= & >=。第二件事,你需要把每一个条件包装成这样

df['<= 18'] = df['rider_age'].apply(lambda x: 1 if x <= 18 else 0)
df['19-24'] = df['rider_age'].apply(lambda x: 1 if (x >=19) & (x <= 24) else 0)
df['25-35'] = df['rider_age'].apply(lambda x: 1 if (x >=25) & (x <= 35) else 0)
df['36-50'] = df['rider_age'].apply(lambda x: 1 if (x >=36) & (x <= 50) else 0)
df['51-59'] = df['rider_age'].apply(lambda x: 1 if (x >=51) & (x <= 59) else 0)
df['60+'] =   df['rider_age'].apply(lambda x: 1 if x >=60 else 0)

相关问题 更多 >