简体   繁体   中英

Perform Pandas Goupby and Percentage Increase/Decrease

I have Dataframe as below:

           Date      Symbol      Quantity        Volume
0    07-04-2020         ACC       1579268        554047
1    08-04-2020         ACC       2153627        586886
2    09-04-2020         ACC       2658885       1128891
3    07-04-2020    ADANIENT       2463525        408903
4    08-04-2020    ADANIENT       3237290        255480
5    09-04-2020    ADANIENT       2359528        335061

I want to perform groupby on 'Symbol' and calculate percentage increase or decrease from 1st date like (07-04-2020 in my example) for subsequent rows.

I want result like below:

    Date         Symbol    Quantity  Volume  PctCH_Qty    PctCH_Vol
0   07-04-2020      ACC     1579268  554047          0           0   
1   08-04-2020      ACC     2153627  586886      36.37        5.93 
2   09-04-2020      ACC     2658885  1128891     68.36      103.75 
3   07-04-2020  ADANIENT    2463525  408903          0           0   
4   08-04-2020  ADANIENT    3237290  255480      31.41      -37.52 
5   09-04-2020  ADANIENT    2359528  335061      -4.22      -18.06 

Idea is divide first value per groups by GroupBy.transform and first , subtract 1 , multiple 100 and last round:

cols = ['Quantity','Volume']
df[['PctCH_Qty','PctCH_Vol']] = (df[cols].div(df.groupby('Symbol')[cols]
                                         .transform('first'), axis=0)
                                         .sub(1)
                                         .mul(100)
                                         .round(2))
print (df)
         Date    Symbol  Quantity   Volume  PctCH_Qty  PctCH_Vol
0  07-04-2020       ACC   1579268   554047       0.00       0.00
1  08-04-2020       ACC   2153627   586886      36.37       5.93
2  09-04-2020       ACC   2658885  1128891      68.36     103.75
3  07-04-2020  ADANIENT   2463525   408903       0.00       0.00
4  08-04-2020  ADANIENT   3237290   255480      31.41     -37.52
5  09-04-2020  ADANIENT   2359528   335061      -4.22     -18.06

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM