Skip to content
Advertisement

Pandas cleaner syntax

I would like to replace the following syntax with a cleaner, chained syntax – perhaps using .pipe (similar to dplyr library in R):

Sample dataset:

dt = pd.DataFrame({
    "PACK_STR": ['112', '112', '112', '134', '145', '134'],
    "FLAG_MODE_SUM_PCK": [1, 0, 1, 1, 1, 0]
})

Code to replace by piping:

packs_mode_sum_pck = dt.groupby(['PACK_STR']).FLAG_MODE_SUM_PCK.sum().reset_index().rename(columns={'FLAG_MODE_SUM_PCK':'OCCUR_MODE_SUM_PCK'})  
dt = dt.merge(packs_mode_sum_pck, how="left", on='PACK_STR')

Expected output:

    PACK_STR    FLAG_MODE_SUM_PCK   OCCUR_MODE_SUM_PCK
0   112                 1                  2
1   112                 0                  2
2   112                 1                  2
3   134                 1                  1
4   145                 1                  1
5   134                 0                  1

Advertisement

Answer

Here are two elegant ways to get your output:

def ssum(grp):
   grp['OCCUR_MODE_SUM_PCK'] = grp['FLAG_MODE_SUM_PCK'].sum()
   return grp
dt.groupby('PACK_STR').apply(ssum)

or

dt['OCCUR_MODE_SUM_PCK'] = dt.groupby('PACK_STR')['FLAG_MODE_SUM_PCK'].transform(sum)
dt
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement