What you want to do is actually again a groupby (on the result of the first groupby): sort and take the first three elements per group.
Starting from the result of the first groupby:
In [60]: df_agg = df.groupby(['job','source']).agg({'count':sum})
We group by the first level of the index:
In [63]: g = df_agg['count'].groupby('job', group_keys=False)
Then we want to sort (‘order’) each group and take the first three elements:
In [64]: res = g.apply(lambda x: x.sort_values(ascending=False).head(3))
However, for this, there is a shortcut function to do this, nlargest
:
In [65]: g.nlargest(3) Out[65]: job source market A 5 D 4 B 3 sales E 7 C 6 B 4 dtype: int64
So in one go, this looks like:
df_agg['count'].groupby('job', group_keys=False).nlargest(3)
Related Posts:
- how to sort pandas dataframe from one column
- How to groupby based on two columns in pandas?
- Pandas group-by and sum
- Count unique values per groups with Pandas
- Pandas group-by and sum
- Pandas ‘count(distinct)’ equivalent
- Count unique values using pandas groupby
- Count unique values per groups with Pandas [duplicate]
- Find the unique values in a column and then sort them
- How do I sort a dictionary by value?
- How do I sort a dictionary by value?
- How to reset index in a pandas dataframe? [duplicate]
- How to deal with SettingWithCopyWarning in Pandas
- How to deal with SettingWithCopyWarning in Pandas
- How to iterate over rows in a DataFrame in Pandas
- pandas read_json: “If using all scalar values, you must pass an index”
- How to iterate over rows in a DataFrame in Pandas
- Writing a pandas DataFrame to CSV file
- ImportError: No module named pandas. Pandas installed pip
- “Series objects are mutable and cannot be hashed” error
- TypeError: ‘Series’ objects are mutable, thus they cannot be hashed problemwith column
- How to replace NaN values by Zeroes in a column of a Pandas Dataframe?
- ValueError: Length of values does not match length of index | Pandas DataFrame.unique()
- Convert Python dict into a dataframe
- re.sub erroring with “Expected string or bytes-like object”
- How do I select rows from a DataFrame based on column values?
- DataFrame constructor not properly called! error
- Python pandas groupby aggregate on multiple columns, then pivot
- Error”Can only compare identically-labeled Series objects” and sort_index
- Finding median of list in Python
- Python Pandas – Missing required dependencies [‘numpy’] 1
- ‘DataFrame’ object has no attribute ‘sort’
- Syntax behind sorted(key=lambda: …)
- How to read a .xlsx file using the pandas Library in iPython?
- Get total of Pandas column
- Plot pie chart and table of pandas dataframe
- Type error: cannot convert the series to
- TypeError: ‘DataFrame’ object is not callable
- How to check whether a pandas DataFrame is empty?
- Convert columns to string in Pandas
- Change column type in pandas
- Using a comparator function to sort
- What does axis in pandas mean?
- AttributeError: Can only use .dt accessor with datetimelike values
- Combine two columns of text in pandas dataframe
- Python: pandas merge multiple dataframes
- How to count the NaN values in a column in pandas DataFrame
- xlrd.biffh.XLRDError: Excel xlsx file; not supported
- Pandas: change data type of Series to String
- Pandas – DataFrame object is not callable
- Selecting with complex criteria from pandas.DataFrame
- Convert pandas data frame to series
- module ‘pandas’ has no attribute ‘rolling_mean’
- How do I combine two dataframes?
- How to sort a list of objects based on an attribute of the objects?
- Normalize columns of pandas data frame
- Converting strings to floats in a DataFrame
- Normalize columns of pandas data frame
- How to add an empty column to a dataframe?
- Pandas join issue: columns overlap but no suffix specified
- How to apply a function to two columns of Pandas dataframe
- Convert categorical data in pandas dataframe
- pandas create new column based on values from other columns / apply a function of multiple columns, row-wise
- SettingWithCopyWarning even when using .loc[row_indexer,col_indexer] = value
- Loading a file with more than one line of JSON into Pandas
- OSError: Initializing from file failed on csv in Pandas
- ValueError: Expected object or value when reading json as pandas dataframe
- Insert a row to pandas dataframe
- How to save a Seaborn plot into a file
- Subtract two columns in dataframe
- How to check if a column exists in Pandas
- pandas DataFrame: replace nan values with average of columns
- Pandas error “Can only use .str accessor with string values”
- Python data structure sort list alphabetically
- How to get row number in dataframe in Pandas?
- Efficiently sorting a numpy array in descending order?
- AttributeError: ‘Series’ object has no attribute ‘reshape’
- How to convert column with dtype as object to string in Pandas Dataframe
- Coalesce values from 2 columns into a single column in a pandas dataframe
- Unknown format code ‘f’ for object of type ‘str’- Folium
- Pandas: sum up multiple columns into one column without last column
- python pandas remove duplicate columns
- Convert Pandas Column to DateTime
- matplotlib: plot multiple columns of pandas data frame on the bar chart
- Concat DataFrame Reindexing only valid with uniquely valued Index objects
- Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support
- Move column by name to front of table in pandas
- Pandas unstack problems: ValueError: Index contains duplicate entries, cannot reshape
- Python: Convert timedelta to int in a dataframe
- Must have equal len keys and value when setting with an iterable
- Pandas dataframe groupby plot
- Calculate weighted average using a pandas/dataframe
- Got continuous is not supported error in RandomForestRegressor
- ValueError: multiclass format is not supported
- How do operator.itemgetter() and sort() work?
- How to convert .sav file into csv file
- ValueError: Must pass DataFrame with boolean values only
- Convert list of dictionaries to a pandas DataFrame
- Python Pandas : pivot table with aggfunc = count unique distinct
- AttributeError: ‘Series’ object has no attribute ‘split’ error in sending emails