英文:
How to get the max column values count
问题
以下是您期望的输出:
item_name count
Steak Salad Bowl 2
Meat Salad Bowl 1
英文:
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
答案1
得分: 1
使用boolean indexing
来根据max
值进行筛选,然后使用Series.value_counts
,对于DataFrame
使用DataFrame.rename_axis
和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
或者对于计数,使用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
以上是代码的翻译部分。
英文:
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
答案2
得分: 1
使用nlargest(n)
:
test.nlargest(1, columns='item_price', keep='all')['item_name'].value_counts()
输出:
Steak Salad Bowl 2
Meat Salad Bowl 1
Name: item_name, dtype: int64
英文:
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
答案3
得分: 1
使用 value_counts() 和 head() 和 reset_index() 和 rename()
pd.DataFrame(test['item_name'].value_counts().head(2).reset_index().rename(columns = {'index': 'item_name', 'item_name' : 'count'}))
输出
item_name count
0 牛排沙拉碗 2
1 巴巴科亚沙拉碗 1
<details>
<summary>英文:</summary>
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
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论