how to calculate the sum of the particular value of column in data frame in python.
eg:
this is an excel file loaded into a dataframe.
Cloth type | Size | Quantity | Color |
Shirt | Small | 2 | Red |
Jacket | X-large | 5 | Grey |
Pantsuit | Medium | 1 | Green |
Shirt | Medium | 10 | Blue |
Shirt | Small | 5 | Green |
Cardigan | Large | 3 | White |
Pantsuit | Small | 2 | Pink |
Cardigan | Large | 6 | Red |
Jacket | Medium | 4 | Blue |
a. How to create a dataframe with 2 columns: cloth type, Total quantity of that cloth (sum)?
eg: for the above record the output should be as follows:
Cloth type Quantity
Shirt 17
Jacket 9
Pantsuit 3
Cardigan 9
df1=df.groupby(by="Cloth type").sum()
print(df1)
output -
Quantity Cloth type Cardigan 9 Jacket 9 Pantsuit 3 Shirt 17
Explanation :
We use groupby function to group dataframe by column = Cloth type and then we use sum() function to sum rest of the column values.Instead of sum() , you can even use other statistical functions like mean(),max(),min()
Get Answers For Free
Most questions answered within 1 hours.