Reputation:
test dataframe is below
test=pd.DataFrame({'item_name':['Steak Salad Bowl','Steak Salad Bowl','Barbacoa Salad Bowl','Meat Salad Bowl'],'item_price':[9.39,9.39,9.19,9.39]})
grps = [grp for _, grp in test.groupby('item_name', sort=False)]
print(grps[0],grps[0].shape[0])
My Expected out
item_name count
Steak Salad Bowl 2
Meat Salad Bowl 1
Upvotes: 0
Views: 628
Reputation: 642
Using value_counts() and head() and reset_index() and rename()
pd.DataFrame(test['item_name'].value_counts().head(2).reset_index().rename(columns = {'index': 'item_name', 'item_name' : 'count'}))
Output
item_name count
0 Steak Salad Bowl 2
1 Barbacoa Salad Bowl 1
Upvotes: 1
Reputation: 13387
Using nlargest(n)
:
test.nlargest(1, columns='item_price', keep='all')['item_name'].value_counts()
Output:
Steak Salad Bowl 2
Meat Salad Bowl 1
Name: item_name, dtype: int64
Upvotes: 1
Reputation: 862911
Use boolean indexing
for filtering by max
values, then Series.value_counts
and for DataFrame
DataFrame.rename_axis
with DataFrame.reset_index
:
df = (test.loc[test['item_price'].eq(test['item_price'].max()), 'item_name']
.value_counts()
.rename_axis('item_name')
.reset_index(name='count'))
print (df)
item_name count
0 Steak Salad Bowl 2
1 Meat Salad Bowl 1
Or for count use GroupBy.size
:
df = (test[test['item_price'].eq(test['item_price'].max())]
.groupby('item_name')
.size()
.reset_index(name='count'))
print (df)
item_name count
0 Meat Salad Bowl 1
1 Steak Salad Bowl 2
Upvotes: 1