多条件循环Python

2024-05-28 20:09:23 发布

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

使用Python的滞后经验让我很难完成这个循环。这是数据帧https://1drv.ms/u/s!AlPw3RIiTz1ChRo9YO4kYCI7n0r0?e=OeiLgx

我想再增加一列('customer_type'),其中包含字符串描述(可以是'New_Guest','reptative with cancelations','reptative NO cancelations')。需满足的条件:

  • 新客人-“是否重复客人”==0和“先前取消客人”==0
  • 与取消重复-“是重复的客人”==1和“以前的取消”>;0
  • 重复无取消-“是否重复\u客人”==1和“以前的\u取消”==0

我尝试了第一个条件,但没有成功

for i in df_test.loc[:,'customer_type'] :
    if ((df_test['is_repeated_guest']==0) & (df_test['previous_cancellations']==0)).all() :
        df_test.loc[:,'customer_type'] = 'New Guest'
    else : df_test.loc[:,'customer_type'] = 0

有人有什么建议吗


Tags: 数据httpstestdfnewtypecustomer经验
1条回答
网友
1楼 · 发布于 2024-05-28 20:09:23

您可以过滤df并设置列值,而无需使用带有df.loc[condition, column_name] = new_value的循环。在你的情况下,它看起来像这样

df['customer_type'] = ''  # add new column
df.loc[(df['is_repeated_guest']==0) & (df['previous_cancellations']==0), 'description'] = 'New_Guest'
# add your other two conditions

您还可以考虑在创建新列时添加默认的“CuuleType类型”,以防在列出的三种情况下出现情况。例如,您是否曾经有过“is_repeaded_guest”==0而“previous_cancellations”==1

相关问题 更多 >

    热门问题