Kenny
Kenny

Reputation: 88

Pandas group and sum values

This ist my example Table imported from a CSV

Name    hours   work
User1   2       Kiwi
User1   5       Melon
...
User1   3       Kiwi

And this is my desired output:

Total Kiwi:  
User1   5   

I guess it is possible with a right join or a groupby. But I cant relize it to real code. I tried something like this

ou = pd.DataFrame([[ou["work"].sum()["kiwi"]]])

Upvotes: 1

Views: 493

Answers (1)

jezrael
jezrael

Reputation: 862591

You need:

df = df.groupby(['Name','work'])['hours'].sum().unstack()
print (df)
work   Kiwi  Melon
Name              
User1     5      5

Or:

df = df.pivot_table(index='Name', columns='work', values='hours', aggfunc='sum')
print (df)

work   Kiwi  Melon
Name              
User1     5      5

And then:

print (df[['Kiwi']])
work   Kiwi
Name       
User1     5

Upvotes: 2

Related Questions