I am trying to replicate PROC SUMMARY like results in Python and used below function as already available on Stack Overflow :
def wmean_grouped2 (group, var_name_in, var_name_weight):
d = group[var_name_in]
w = group[var_name_weight]
return (d * w).sum() / w.sum()
FUNCS = { "mean" : np.mean ,
"sum" : np.sum ,
"count" : np.count_nonzero }
def my_summary2 (
data ,
var_names_in ,
var_names_out ,
var_functions ,
var_name_weight = None ,
var_names_group = None ):
result = pd.DataFrame()
if var_names_group is None:
grouped = data.groupby (lambda x: True)
else:
grouped = data.groupby (var_names_group)
for var_name_in, var_name_out, var_function in \
zip(var_names_in,var_names_out,var_functions):
if var_function == "wsum":
func = lambda x : wmean_grouped2 (x, var_name_in, var_name_weight)
result[var_name_out] = pd.Series(grouped.apply(func))
else:
func = FUNCS[var_function]
result[var_name_out] = grouped[var_name_in].apply(func)
return result
I have called function as below:
print(my_summary2 (
data=df,
var_names_in=["sal","sal","age"] ,
var_names_out=[
"COUNT","SAL","age"
] ,
var_functions=["count","sum","sum"] ,
var_name_weight="val_1" ,
var_names_group=["name"]
))
and getting below output:
COUNT SAL age
name
Arik 1 100 32
David 2 260 88
John 2 500 67
Peter 1 100 33
Could you please help in generating below output: (i) New line after column "name" (ii) Total sun of each variable after inserting hyphens(-)
name COUNT SAL age
Arik 1 100 32
David 2 260 88
John 2 500 67
Peter 1 100 33
---- ----- ----
6 960 220
I was able to generate each column sum by using below code:
result.loc['Total'] = result.select_dtypes(pd.np.number).sum()
before returning the result.
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.