Python sum values in column given a condition

Question:

Suppose I have 2 column like:

Item Code    Units Sold
   179           1
   179           2
   180           1
   180           4
   190           3
   190           5

I want to sum up the values in "Units Sold" if they have the same "Item Code" using python and pandas.

Asked By: Mike Dang

||

Answers:

Do you want something like this:

Item Code    Units Sold
   179           3
   180           5
   190           8

Try this:

df.groupby('Item Code')['Units Sold'].sum()
df.reset_index(inplace=True)
Answered By: Salahuddin
df = df.groupby('Item Code').sum()
df.reset_index(inplace=True)
Answered By: Aman Raheja

One can use Groupby to do this efficiently

Assuming that the dataframe is df

ans = df.groupby(df['Item Code'])['Units Sold'].sum()

This is the output .

Item Code
179    3
180    5
190    8
Name: Units Sold, dtype: int64

Hope this helps!

Answered By: Anwesan De
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.