基于使用三个不同列的条件 if 逻辑的 python 标志

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

我有以下基于谷歌分析数据的 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 的标志。它应该做的是为该 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语句,但没有别走远。

最佳答案

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 将其广播到该组的所有索引中。

关于基于使用三个不同列的条件 if 逻辑的 python 标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46083676/

相关文章:

python - 尽管使用了早期且已经工作的代码,指针仍不向上或向下移动

python - 运行时警告: coroutine 'main' was never awaited error

python selenium 不支持 firefox - 消息 : Can't load the profile. Profile Dir

python - 使用 TRUE 值从 BOOLEAN 列填充数据框列

python - 从(行、列、值)数据创建 Pandas DataFrame

python - Pandas 选择 DataFrame 中的某些列和最后 n 列

python - 在保持内部顺序的同时打乱 DataFrame

oracle - 使用 if 语句 PL/SQL 更新表

C 如何比较 2 个 int

amazon-web-services - 创建资源的AWS cloudformation条件