▶학습내용
*고객세그먼트하기
1) 채널별 아이디별로 총구매금액, 평균금액,최근구매일,구매횟수 구하기
customer_segment=merge_df4.groupby(['customer_id','sales_channel_id']).agg(sum_price=('price','sum'),avg_price=('price','mean'),resent=('t_dat','max'),count=('price','count')).reset_index()
2) 구매횟수 ,구매빈도 구하기
상위30% 기준으로 하여 구해 보았다.
customer_segment1=customer_segment[customer_segment['sales_channel_id']==1] # 채널별로 나눠서 해야하니까 조건을 걸어줘야함 한사람이 온라인에서 구매했을수도 있고 오프라인에서 구매했을 수도 있으니까
customer_segment2=customer_segment[customer_segment['sales_channel_id']==2]
price_off1=customer_segment1['sum_price'].quantile(0.7)
price_off2=customer_segment2['sum_price'].quantile(0.7)
count_off1=customer_segment1['count'].quantile(0.7)
count_off2=customer_segment2['count'].quantile(0.7)
처음에는 채널별로 필터링하지않고 하였는데 그렇게하면 한아이디가 온라인에서 구매했을수도있고 오프라인에서 구매했을수도 있어서 정확한 데이터가 나오지 않기 때문에 채널별로 필터링 해주어야 했다.
customer_segment1['price/HL']=np.where(customer_segment1['sum_price']>=price_off1,'High','Low')
customer_segment2['price/HL']=np.where(customer_segment2['sum_price']>=price_off2,'High','Low')
customer_segment1['count/HL']=np.where(customer_segment1['count']>=count_off1,'High','Low')
customer_segment2['count/HL']=np.where(customer_segment2['count']>=count_off2,'High','Low')
그리고나서, 조건을 걸어주어서 구매빈도와 횟수를 high,low로 나누었다.
3) 채널1,채널2 병합
customer_segment=pd.concat([customer_segment1,customer_segment2],axis=0,ignore_index=True)
나누었던 채널을 병합해주었다.
4) 회원수구하기
channel_segement_counts=customer_segment.groupby(['sales_channel_id','price/HL','count/HL']).size().reset_index(name='customer_count')
채널별,구매빈도별,구매금액별로 그룹바이를 해준 후, 각각에 수를 세어주고 customer_count 라는 컬럼명으로 지정해주었다.
sales_channel_id price/HL count/HL customer_count
| 1 | High | High | 35727 |
| 1 | High | Low | 10916 |
| 1 | Low | High | 17672 |
| 1 | Low | Low | 90623 |
| 2 | High | High | 71781 |
| 2 | High | Low | 2660 |
| 2 | Low | High | 42664 |
| 2 | Low | Low | 123900 |
5) 채널별 총 회원수 구하기
channel_segement_counts['total_customers']= channel_segement_counts.groupby('sales_channel_id')['customer_count'].transform('sum')
6) 구매금액별,구매횟수별 고객이 전체중 몇프로 차지하는지 구하기
channel_segement_counts['percentage']=channel_segement_counts['customer_count']/channel_segement_counts['total_customers']*100
sales_channel_id price/HL count/HL customer_count total_customers percentage
| 1 | High | High | 35727 | 154938 | 23.058901 |
| 1 | High | Low | 10916 | 154938 | 7.045399 |
| 1 | Low | High | 17672 | 154938 | 11.405853 |
| 1 | Low | Low | 90623 | 154938 | 58.489848 |
| 2 | High | High | 71781 | 241005 | 29.784029 |
| 2 | High | Low | 2660 | 241005 | 1.103712 |
| 2 | Low | High | 42664 | 241005 | 17.702537 |
| 2 | Low | Low | 123900 | 241005 | 51.409722 |