簡體   English   中英

根據多個條件在 python dataframe 中添加列

[英]Adding a column in a python dataframe based on multiple conditions

我有這個名為 unique_customers 的unique_customers

我還定義了 2 個變量; VIPpreferred

我想添加另一個包含特定字符串的列:

  • 如果amount_spend >= VIP中的值,我想添加 VIP
  • 如果amount_spend >= preferred中的值,我想添加首選

這就是我所做的:

unique_customers['Customer Status'] = 
    np.where(unique_customers[['amount_spent']] >= VIP,
             'VIP', (unique_customers[['amount_spent']] >= preferred,
                     'preferred', 'other'))

這是行不通的。 我收到以下錯誤:

ValueError: Wrong number of items passed 3, placement implies 1

我在這里做錯了什么?

你看, numpy.where需要三個 arguments: (condition, value_if_true, value_if_false) 您正在將一個包含三個元素的tuple傳遞給第三個參數,但我認為您打算這樣做:

unique_customers['Customer Status'] = 
    np.where(unique_customers[['amount_spent']] >= VIP,
             'VIP', 
             np.where(unique_customers[['amount_spent']] >= preferred,
                     'preferred', 
                     'other'))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM