如何基于数据帧中的两列提取数据,并使用Python创建新列?

2024-04-26 18:56:29 发布

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

我的数据框中有两列。“成人”表示酒店房间中成人的数量,“儿童”表示房间中儿童的数量

我想在这两个基础上创建一个新列。 例如,如果df['adults'] == 2 and df[‘children’]==0,新列的值将是“没有孩子的夫妇”。 如果df['adults'] = 2 and df[‘children’]=1,则新列的值将是“与1个子项耦合”

我有大量的数据,我希望代码能够快速运行

有什么建议吗?这是我需要的输入和输出示例

adult children   family_status

2       0       "Couple without children"     
2       0       "Couple without children"
2       1       "Couple with one child"

Tags: and数据df数量孩子酒店基础儿童
1条回答
网友
1楼 · 发布于 2024-04-26 18:56:29

您可以尝试:

df['family_status'] = df.apply(lambda x: 'adult with no child' if (x['adult']==2 and x['children']==0)  
                        else ( 'adult with 1 child' 
                              if (x['adult']==2 and x['children']==1) else ''), axis=1)

希望这对你有帮助

相关问题 更多 >