Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use grouping feature in Excel pivot table function in pandas?

I have a pandas dataframe.

id Score Action_flag
S11 0.585366 Not Traded
P555 0.457778 Not Traded
B28 0.636154 Not Traded
A859 0.000000 Traded
P556 0.761905 Not Traded
Y461 0.333333 Not Traded
S121 0.444444 Not Traded
K481 0.000000 Traded
S122 1.000000 Not Traded
R556 0.000000 Traded
R627 0.602778 Traded

In excel using pivot table and grouping I was able to do this.

How to achieve this using pandas

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

And pivot table enter image description here

>Solution :

IIUC, you could create bins using pd.cut, then use crosstab to get the counts each each action flag. Finally, assign the row-wise totals to a new column "Grand_total":

out = pd.crosstab(pd.cut(df['Score'], np.linspace(0,1,21), include_lowest=True), df['Action_flag']).assign(Grand_total=lambda x: x.sum(axis=1))

Output:

Action_flag     Not Traded  Traded  Grand_total
Score                                          
(-0.001, 0.05]           0       3            3
(0.3, 0.35]              1       0            1
(0.4, 0.45]              1       0            1
(0.45, 0.5]              1       0            1
(0.55, 0.6]              1       0            1
(0.6, 0.65]              1       1            2
(0.75, 0.8]              1       0            1
(0.95, 1.0]              1       0            1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading