I have a dataframe below:
JavaScript
x
8
1
Year Material Total_amount Customer_code
2
2019 Table 20 00147
3
2019 Chair 25 00159
4
2019 Table 20 00160
5
2020 Table 20 00159
6
2020 Spoon 2 00147
7
2020 Fork 2 00147
8
I’m trying to find the customer that keeps coming back
JavaScript
1
8
1
cust = (pd.pivot_table(sd_df,
2
values=['Total Amount','Customer Code'],
3
index=['Year'],
4
aggfunc=[np.sum, len]).reset_index()
5
)
6
cust
7
8
I did this but it returned me this
Edit: I am trying to get the sum of the total amount and the count of the customer code.
Any help is appreciated. Thanks!
Advertisement
Answer
You can use DataFrame.groupby
JavaScript
1
7
1
print(
2
df.groupby('Year').agg(**{
3
"Sum_Total_Amount": ('Total_amount', 'sum'),
4
"Count_Cust_Code": ('Customer_code', 'nunique'),
5
}).reset_index()
6
)
7
JavaScript
1
4
1
Year Sum_Total_Amount Count_Cust_Code
2
0 2019 65 3
3
1 2020 24 2
4