Pandas有效地构建路径

2024-06-16 11:26:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个如下的熊猫数据框,它有两个任意的客户,有2个月的数据(有更多的月)和ATL_标志,这是营销渠道(也有更多):

|App_Flag|ATL_Flag|Cust_No|month1|month2
| 0      |  TV    | 1     | 1    | 0
| 0      |  FB    | 1     | 0    | 0
| 0      |  OOH   | 1     | 1    | 1
| 1      |  RAD   | 2     | 1    | 1
| 1      |  TV    | 2     | 1    | 0
| 1      |  FB    | 2     | 1    | 0

我的目标是构建ATL_标志,以便

1)如果特定客户的月值为1,则集群/连接ATL_标志。例如,从上面的示例中,对于month1&;客户1,字符串应该是:TVOOH,对于month2和客户1,字符串应该是:OOH(month2向量只有一个1,对应于OOH)

2)然后,将这两个结果字符串组合在一起两个(或更多)月,如下所示:TVOOH->;哦

最终结果应该是这样的:

|App_Flag|Cust_No|Path | 0 | 1 | TVOOH->OOH | | 1 | 2 | RADTVFB->RAD|

我用以下方法尝试过,但似乎太慢太复杂:

def str_sum(channel):
    return '>'.join(channel['c_path'])

wrk_data_temp = pd.melt(work_data_temp[['cust_no', 'ATL_Flag', 'max_exp_1_mnth', 'max_exp_2_mnth']], id_vars=['cust_no', 'ATL_Flag'], value_vars=['max_exp_1_mnth', 'max_exp_2_mnth'], value_name='key')
wrk_data_temp['variable'] = wrk_data_temp['variable'].str.extract(r'([\d]+)').astype(int)
wrk_data_temp['c_path'] = wrk_data_temp.sort_values(['cust_no', 'variable', 'ATL_Flag'])[wrk_data_temp.key == 1][['cust_no', 'ATL_Flag', 'variable']].groupby(['cust_no', 'variable']).transform('sum')
wrk_data_temp2 = wrk_data_temp[['cust_no', 'variable', 'c_path']].drop_duplicates()
wrk_data_temp3 = wrk_data_temp2.dropna()
final = pd.DataFrame(wrk_data_temp3[['cust_no', 'c_path']].groupby('cust_no').apply(str_sum))

Tags: pathnodata客户标志variabletempmax
1条回答
网友
1楼 · 发布于 2024-06-16 11:26:55

首先获取所有具有month的列,用ATL_Flag列替换1值,并为每个组聚合join,然后用另一个join将列连接在一起:

c = df.filter(like='month').columns
df[c] = np.where(df[c].astype(bool), df['ATL_Flag'].values[:, None], '')

df1 = (df.groupby(['App_Flag','Cust_No'])[c]
         .agg(''.join)
         .apply('>'.join, axis=1)
         .reset_index(name='Path'))
print (df1)

   App_Flag  Cust_No         Path
0         0        1    TVOOH>OOH
1         1        2  RADTVFB>RAD

编辑:对于组中的忽略0值:

print (df)
   App_Flag ATL_Flag  Cust_No  month1  month2  month3
0         0       TV        0       0       0       0
1         0       FB        1       0       0       0
2         0      OOH        1       0       1       1
3         1      RAD        2       1       1       0
4         1       TV        2       1       0       0
5         1       FB        3       1       0       1

c = df.filter(like='month').columns
df[c] = np.where(df[c].astype(bool), df['ATL_Flag'].values[:, None], '')

df1 = (df.groupby(['App_Flag','Cust_No'])[c]
         .agg(''.join)
         .apply(lambda x: '>'.join(y for y in x if y != ''), axis=1)
         .reset_index(name='Path')
         )

print (df1)
   App_Flag  Cust_No       Path
0         0        0           
1         0        1    OOH>OOH
2         1        2  RADTV>RAD
3         1        3      FB>FB

相关问题 更多 >