Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
158 views
in Technique[技术] by (71.8m points)

python - How do I use sum and count functions together on different columns in my data frame function?

My data frame is the following:

Advertiser      Product             Price
Company1        A                   10
Company1        A                   10
Company1        B                   8
Company2        C                   5
Company3        D                   3

My current function is:

top_5_products = df.groupby(['Advertiser'])['Product'].value_counts(ascending = False).head(5)

It outputs the following:

Advertiser      Product
Company 1       A   2
                B   1
Company 2       C   1
Company 3       D   1

What is the best way to modify my function to give me the sum of the price as well? Example:

Advertiser      Product     Total Price
Company 1       A   2       20
                B   1       8
Company 2       C   1       5
Company 3       D   1       3

I have looked at the .agg method but I'm lacking examples that use different columns. (I'm also not sure if that's the best way to go about it) Thanks!

Edit***

df.groupby(['Advertiser', 'Product']).agg({'Product': 'count', 'Price': 'sum'}).head(5)

doesn't work as it is no longer sorted...

question from:https://stackoverflow.com/questions/65829953/how-do-i-use-sum-and-count-functions-together-on-different-columns-in-my-data-fr

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

groupby with agg

df.groupby(['Advertiser', 'Product']).agg({'Product': 'count', 'Price': 'sum'})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...