実現したいこと
chanelデータをもとに、webのみ、店頭のみ、どちらも利用 に分けた新たなカラム(main_channel)を作りたい。
試したこと
pandasのgroupby関数を使用して、どうにか加工できないか模索している状況です。
希望のデータ構造
python
1import pandas as pd 2 3df = pd.DataFrame([[1,'2018-12-17','web','どちらも利用'], 4 [1,'2018-12-18','web','どちらも利用'], 5 [1,'2018-12-10','store','どちらも利用'], 6 [2,'2019-1-10','store','店頭のみ'], 7 [2,'2019-1-10','store','店頭のみ']], 8 columns=['no','sale_date','channel','main_channel']) 9 10# id sale_date channel main_channel 11# 1 2018-12-17 web どちらも利用 12# 1 2018-12-18 web どちらも利用 13# 1 2018-12-10 store どちらも利用 14# 2 2019-1-10 store 店頭のみ 15# 2 2019-1-10 store 店頭のみ
main_chanelの条件
どちらも利用:同idでchannelカラムにweb,storeが存在する。
店頭のみ:同idでchannelカラムにstoreのみが存在する。
webのみ:同IDでchannelカラムにwebのみが存在する。
### 発生するエラー
python
1 2pdf = pd.pivot_table(df.loc[:, ["no", "channel"]], index="no", 3 columns="channel", aggfunc=len) 4 5# > print(pdf) 6# channel store web 7# no 8# 1 1.0 2.0 9# 6 2.0 NaN 10# 22 NaN 2.0 11 12 13def conv_func(row): 14 if row["store"] > 0 and row["web"] > 0: 15 return "どちらも利用" 16 elif row["store"] > 0: 17 return "店頭のみ" 18 elif row["web"] > 0: 19 return "Webのみ" 20 else: 21 raise RuntimeError(str(row)) 22 23 24id_main_channel_dict = dict(pdf.apply(conv_func, axis=1)) # dict: ID -> main_channel 25 26out: 27KeyError: ('web', 'occurred at index 07562705') 28
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2019/08/09 02:55
2019/08/09 03:03
退会済みユーザー
2019/08/13 02:09