pandas - Python pivoting table from dataframe -


i have problem aggregating , pivoting table pandas dataframe, here result table:

customer dataframe:

    customerid  x_value         y_value     z_value 0   12346       1               1           1 1   12747       5               1           5 2   12748       5               5           5 3   12749       5               1           5 4   12820       5               1           4 5   12821       2               1           1 

what want pivoting into:

enter image description here

how can accomplished this?

thank you

using pivot_table, use fill_value=0 fill nans 0

in [2198]: df.pivot_table(index=['x_value', 'y_value'], columns=['z_value'],                            values='customerid', aggfunc='count', fill_value=0) out[2198]: z_value          1  4  5 x_value y_value 1       1        1  0  0 2       1        1  0  0 5       1        0  1  2         5        0  0  1 

or, using groupby , unstack

in [2199]: df.groupby(['x_value', 'y_value', 'z_value']).size().unstack(fill_value=0) out[2199]: z_value          1  4  5 x_value y_value 1       1        1  0  0 2       1        1  0  0 5       1        0  1  2         5        0  0  1 

hacky way missing x_value

in [2218]: (df.groupby(['x_value', 'y_value', 'z_value']).size().unstack(fill_value=0)               .unstack(level=0, fill_value=0).stack()               .reorder_levels(['x_value', 'y_value'], axis=0)) out[2218]: z_value          1  4  5 x_value y_value 1       1        1  0  0 2       1        1  0  0 5       1        0  1  2 1       5        0  0  0 2       5        0  0  0 5       5        0  0  1 

Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -