Home > Software engineering >  Python sum values in column given a condition
Python sum values in column given a condition

Time:08-29

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.

CodePudding user response:

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!

CodePudding user response:

Do you want something like this:

Item Code    Units Sold
   179           3
   180           5
   190           8

Try this:

df.groupby('Item Code').sum()
df.reset_index(inplace=True)

CodePudding user response:

df = df.groupby('Item Code').sum()
df.reset_index(inplace=True)
  • Related