【问题标题】:python flag based on conditional if logic using three different columns基于条件if逻辑的python标志使用三个不同的列
【发布时间】:2017-09-06 20:16:53
【问题描述】:

我有以下基于谷歌分析数据的 df:

Customer | transaction_id | medium   | first_transaction_flag
ABC        12345            organic      Y
ABC        23456            email        0    
ABC        34567            organic      0
BCD        45678            organic      0
BCD        56789            referral     0

在上面的 df 中,交易 12345 的 first_transaction_flag 为 Y,这意味着这是客户的第一笔交易。

我需要添加第二个标记为 first_channel 的标志。它应该做的是为该渠道的一个客户标记,在该渠道中,所有后续交易都将其作为 first_channel = Y 获得。这将是输出:

Customer | transaction_id | medium   | first_transaction_flag | first_channel
ABC        12345            organic      Y                       Y
ABC        23456            email        0                       0
ABC        34567            organic      0                       Y             
BCD        45678            organic      0                       0
BCD        56789            referral     0                       0

基本上,这将是一个条件 if 语句:如果 first_transaction_flag = Y,则将客户和媒介的相同组合标记为 Y。我试图考虑是否可以使用 loc 或 np.where 语句,但没有不要走太远。

【问题讨论】:

    标签: python pandas if-statement conditional where-clause


    【解决方案1】:
    cols = ['Customer', 'medium']
    col = 'first_transaction_flag'
    df.assign(first_channel=df.groupby(cols)[col].transform('first'))
    
      Customer  transaction_id    medium first_transaction_flag first_channel
    0      ABC           12345   organic                      Y             Y
    1      ABC           23456     email                      0             0
    2      ABC           34567   organic                      0             Y
    3      BCD           45678   organic                      0             0
    4      BCD           56789  referral                      0             0
    

    说明

    'first' 将获取组内的第一个结果,transform 在该组的所有索引中广播它。

    【讨论】:

    • 非常感谢 - 您介意在语句的最后解释“first”以及您在哪里定义 first_channel 列应显示匹配的 Y 吗?
    • 我添加了一些解释
    • 太好了 - 谢谢!我刚刚运行它,它给了我 Y/N - 这是完美的;非常感谢
    • 如果表格正确排序,则此方法有效,即第一个事务的first_transaction_flag 设置为Y。为了确保所需的行为,您可能需要考虑通过 df.sort_values(['Customer', 'first_transaction_flag'], ascending=[True, False]) 进行预排序
    • 谢谢@Alexander - 我不知道,我巨大的 df 绝对不是这样排序的 - 你为我省去了很多后来的故障排除,谢谢!
    【解决方案2】:

    可能有更好的方法来解决您的问题,但这也很有效:

    fc = df[df['first_transaction_flag'] == 'Y'][['Customer', 'medium']]
    fc['first_channel'] = 'Y'
    df = df.merge(fc, how='outer').fillna(0)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-06
      • 1970-01-01
      • 2020-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多