Pandas percentage of total with groupby

Update 2022-03 This answer by caner using transform looks much better than my original answer! df[‘sales’] / df.groupby(‘state’)[‘sales’].transform(‘sum’) Thanks to this comment by Paul Rougieux for surfacing it. Original Answer (2014) Paul H’s answer is right that you will have to make a second groupby object, but you can calculate the percentage in a simpler … Read more

Converting a Pandas GroupBy output from Series to DataFrame

g1 here is a DataFrame. It has a hierarchical index, though: In [19]: type(g1) Out[19]: pandas.core.frame.DataFrame In [20]: g1.index Out[20]: MultiIndex([(‘Alice’, ‘Seattle’), (‘Bob’, ‘Seattle’), (‘Mallory’, ‘Portland’), (‘Mallory’, ‘Seattle’)], dtype=object) Perhaps you want something like this? In [21]: g1.add_suffix(‘_Count’).reset_index() Out[21]: Name City City_Count Name_Count 0 Alice Seattle 1 1 1 Bob Seattle 2 2 2 Mallory … Read more

Get statistics for each group (such as count, mean, etc) using pandas GroupBy?

Quick Answer: The simplest way to get row counts per group is by calling .size(), which returns a Series: df.groupby([‘col1′,’col2’]).size() Usually you want this result as a DataFrame (instead of a Series) so you can do: df.groupby([‘col1’, ‘col2’]).size().reset_index(name=”counts”) If you want to find out how to calculate the row counts and other statistics for each … Read more