python astype+groupby+sign+agg

https://www.pythonheidong.com/blog/article/298816/6371146b31b4b3d510d0/

python astype+groupby+sign+agg

import pandas as pd
import numpy as np
df={'ACCOUNT': ['1','2','2','1','1'],
     'AMOUNT':  ['-2','2','-1','2','2'],
     'STATUS' : ['1','0','0','1','1']}
df=pd.DataFrame(df).astype(int) ##直接运行后面会报错
print(df)
print('-'*40)
data1=df.groupby(['ACCOUNT', 'STATUS', np.sign(df.AMOUNT)]).AMOUNT.agg(['count', 'sum'])
print(data1)
print('-'*40)
data=df.groupby(['ACCOUNT', 'STATUS', np.sign(df.AMOUNT)]).AMOUNT.agg(['count', 'sum']).unstack()
print(data)

python astype+groupby+sign+agg

import pandas as pd
import numpy as np
df={'ACCOUNT': ['1','2','2','1','1'],
     'AMOUNT':  ['-2','2','-1','2','2'],
     'STATUS' : ['1','0','0','1','1']}
df=pd.DataFrame(df).astype(int) ##直接运行后面会报错
prin
df.groupby(
    ['ACCOUNT', 'STATUS', np.sign(df.AMOUNT).map({-1: '<0', 0: '=0', 1: '>0'})]
).AMOUNT.agg(['count', 'sum']).rename(
    columns=dict(count='COUNT', sum='AMOUNT')
).unstack().abs().pipe(
    lambda d: d.set_axis(d.columns.map('{0[0]}{0[1]}'.format), 1, inplace=False)
)

python astype+groupby+sign+agg

上一篇:pregel+ 核心源码注释


下一篇:pandas dataframe数据聚合groupby、agg、privot基于sum统计详解及实例