transposing data based on column value using python

Question:

I have web traffic data for a different channel. I want to transpose based on the channel name and get multiple time series.

day    main_channel visits  CR
11/2/2022   a   443645  1.248513488
11/2/2022   b   382870  3.441750617
11/2/2022   c   51249   0.315164766
11/1/2022   a   390267  2.725545677
11/1/2022   b   15361   0.478254073
11/1/2022   c   450734  1.513615502

I would like to have only a single date and transpose values in new columns.

day         a_visits    b_visits    c_visits    a_CR    b_CR    c_CR
11/2/2022   443645  382870  51249   1.248513488 3.441750617 0.315164766
11/1/2022   390267  15361   450734  2.725545677 0.478254073 1.513615502

Can someone help me here please? 🙂

Thank you in advance!

Asked By: sdave

||

Answers:

IF using pandas are fine. you could import your data as csv

df = pd.read_csv('data.csv')
df = df.pivot_table(columns='main_channel', index='day', values=['visits','CR'])
df.columns = ['_'.join(reversed(col)) for col in df.columns.values]

enter image description here

Answered By: amirhm