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

Time:04-22

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

enter image description here

And pivot table enter image description here

CodePudding user response:

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
  • Related