Mitchell Mitchell -4 years ago 41
Python Question

How to create new dataframe out of total values based on specific column value?

Let's say I have a dataframe that looks something like this:

A B C
X U 500
X S 300
X T 200
Y F 20
Y G 980
Z L 400


I would like to use specific values in column A so {X, Y, Y} and based on those values, I'd like to take the row C total sum and output it in a new dataframe. My new dataframe should like something like this

A B
X 1000
Y 1000
Z 400


It is essentially grouping the values by name in column A, taking the total sum of C from each of those values in A, and creating a new dataframe with the name specified in column A with the totals from column C.

I need it to pick up on these values on its own, because imagine my dataframe has 200 rows and 80 different values in column A.

Answer Source

Use:

df = df.groupby('A', as_index=False)['B'].sum()

Or:

df = df.groupby('A')['B'].sum().reset_index()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download