I have the following dataframe:-
traffic_type date region total_views
desktop 01/04/2018 aug 50
mobileweb 01/04/2018 aug 60
total 01/04/2018 aug 100
desktop 01/04/2018 world 20
mobileweb 01/04/2018 world 30
total 01/04/2018 world 40
I need to group by traffic_type, date, region, and filter the rows with traffic type total and in the same row create a desktop_share column which is total_views of traffic_type==desktop / total views of the traffic_type ==total the rest of the rows are blank for this column.
traffic_type date region total_views desktop_share
desktop 01/04/2018 aug 50
mobileweb 01/04/2018 aug 60
total 01/04/2018 aug 200 0.25
desktop 01/04/2018 world 20
mobileweb 01/04/2018 world 30
total 01/04/2018 world 40 0.5
I have a long approach which works but I am looking for something more precise
based on numpy or just pandas.
My solution:
df1 = df2.loc[df2.traffic_type == 'desktop']
df1 = df1[['date', 'region', 'total_views']]
df1 = df2.merge(df1, how='left', on=['region', 'date'], suffixes=('', '_desktop'))
df1 = df1.loc[df1.traffic_type == 'total']
df1['desktop_share'] = df1['total_views_desktop'] / df1['total_views']
df1 = df1[['date', 'region', 'desktop_share', 'traffic_type']]
dfinal = df2.merge(df1, how='left', on=['region', 'date', 'traffic_type'])
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…