python astype+groupby+sign+agg
作者:互联网
https://www.pythonheidong.com/blog/article/298816/6371146b31b4b3d510d0/
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)
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)
)
标签:STATUS,ACCOUNT,python,print,agg,AMOUNT,np,df,groupby 来源: https://blog.csdn.net/qq_27866857/article/details/111583705