【问题标题】:Multiple conditions Loop Python多个条件循环 Python
【发布时间】:2021-05-29 04:46:43
【问题描述】:

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

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

  • New_Guest - 'is_repeated_guest' ==0 AND 'previous_cancellations'==0
  • 重复取消 - 'is_repeated_guest' ==1 AND 'previous_cancellations' > 0
  • 没有重复取消 - 'is_repeated_guest' ==1 AND 'previous_cancellations'==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

有人有什么建议吗?

【问题讨论】:

    标签: python pandas loops for-loop


    【解决方案1】:

    您可以过滤 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
    

    您还可以考虑在创建新列时添加一个默认的“customer_type”,以防出现上述三种情况之外的情况。例如,您是否曾经拥有 'is_repeaded_guest'==0 而 'previous_cancellations'==1?

    【讨论】:

      猜你喜欢
      • 2011-11-02
      • 1970-01-01
      • 1970-01-01
      • 2014-12-22
      • 1970-01-01
      • 2011-09-02
      • 2015-12-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多