【问题标题】:Create column based on multiple conditions on different columns根据不同列上的多个条件创建列
【发布时间】:2019-10-21 23:19:19
【问题描述】:

基于来自不同列的值的多个条件在数据框中创建列。

我们的目标是了解客户第一次感兴趣的操作是什么时候发生的,这将在 t0 下用 1 表示。

Dataframe 的结构如下:

      cust_id       first_act     prod_1  prod_2   t0
0      1                  1          1              
22     2                                            
23     2                                     1                      
24     2                             1              
25     2                                            
26     3                  1
27     3
28     3
29     4
30     4

我想根据以下条件为列 t0 赋值:

如果客户在 prod_1 下有 1:在它在 prod_1 下有 1 的索引处将值 1 分配给 t0。

如果客户在 prod_1 下没有 1,则检查客户在 prod_2 下是否有 1,如果为真,则在条件为真的索引处分配 1 的值。

最后:如果客户没有 prod_1 或 prod_2,但在 first_act 下确实有 1,则将值 1 分配给在 t0 下 first act 为真的索引。

在这些条件之后,每个客户的 t0 中应该只有一个值。

cust_id 2 的预期输出:

 cust_id       first_act     prod_1  prod_2   t0
0      1            1          1              
22     2            1                                
23     2                               1                      
24     2                       1               1    
25     2                                            
26     3            1
27     3
28     3
29     4
30     4

我尝试使用嵌套的 np.where 语句执行此操作,但效果如下:

df['t0'] = np.where(df['prod_1'] == 1, 1 ,
                         np.where(df['prod_2'] == 1, 1,
                                 np.where(df['first_act'] == 1, 1, 0)))

在多个位置将 1 添加到 t0。

更新

@Jeffyx 我不知道这是否会清除它,但我想到的是:

if prod_1 == 1:
    t0 = 1 at index of prod_1 == 1
if not prod_1 == 1:
    if prod_2 == 1:
        t0 = 1 at index of prod_2 == 1
if not prod_1 == 1 and not prod_2 == 1:
    if first_act == 1:
        t0 = 1 at index of first_act == 1

【问题讨论】:

  • 我不会撒谎,我很难理解您对 ['t0'] 获得 1 的要求,但我知道回答您问题的一种简单方法是使用[链接] (pandas.pydata.org/pandas-docs/stable/reference/api/…) 熊猫 loc。这是一种更新具有多个条件的列的简单方法。
  • 同意@Jeffyx——我通读了要求并检查了我的预期输出是否与您的匹配,但它甚至还没有接近。我会在您更新后再次尝试查看。
  • 我知道这可能会造成混淆。尝试改写,有帮助吗?

标签: python pandas multiple-columns multiple-conditions


【解决方案1】:

您必须找到与您的条件匹配的第一个索引,然后使用该索引在t0 列中设置一个值。

使用 groupby,它给出:

for _, sub in df.groupby(['cust_id']):              # test for each cust_id
    for col in ['prod_1', 'prod_2', 'first_act']:   # test columns in sequence
        tmp = sub[sub[col] == 1]                    # try to match
        if len(tmp) != 0:                           # ok found at least one
            df.loc[tmp.index[0], 't0'] = 1          # set t0 to 1 for first index found
            break

【讨论】:

  • 谢谢,这是完美的。我不知道您可以使用 _ 循环遍历组。
  • groupby 上迭代会返回对(索引、子数据帧)。 - 变量只是表示我不会在这里使用索引。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-11
  • 1970-01-01
  • 2021-08-24
  • 1970-01-01
  • 2021-03-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多