user9364978
user9364978

Reputation:

How to reshape a dataframe into a particular format

I have the following dataframe which I want to reshape:

    year    control   Counts_annee_control
0   2014.0  0         81.0
1   2016.0  1         147.0
2   2016.0  0         168.0
3   2015.0  1         90.0
4   2016.0  1         147.0

I want the control column to be the new index, so I will have only two columns. The year values should be the new columns of the dataframe and finally the Counts_annee_control column will fill the dataframe.

I tried using groupby and transform but I don't think I'm doing it correctly.

Upvotes: 0

Views: 45

Answers (1)

Dakshila Kamalsooriya
Dakshila Kamalsooriya

Reputation: 1401

You are probably looking for pivot_table.

If df is your DataFrame, then this

modified_df = df.pivot_table(
    values='Counts_annee_control', index='control', columns='year'
)

will result in

year     2014.0  2015.0  2016.0
control                        
0          81.0     NaN   168.0
1           NaN    90.0   147.0

Upvotes: 1

Related Questions