pandas 尝试在Python中按部门显示计数

avwztpqn  于 2023-02-27  发布在  Python
关注(0)|答案(2)|浏览(125)

这是一段简单的代码,出于某种原因,我现在想不起来了。我试图按部门按状态计算任务的数量。例如:

Department      Task           Status
   Sales         Sell           Pendiing
   Sales         Presentation   Complete
   Tech          Merge Data     Complete 
   Tech          Consolidate    Pending 
   Tech          Presentation   Complete

这里我想要的是能够在状态栏中按部门细分完成的计数。类似于以下内容:

Department    Status        Count
  Sales       Completed       1
  Tech        Completed       2

到目前为止,我的代码看到了所有部门的计数,但我无法找出分组的最佳方式。
参考代码:

counts = df['Department'].groupby('Status').count()
dkqlctbz

dkqlctbz1#

您需要groupbyDepartmentStatus;如果需要,可以对每个组执行count,对Task列执行rename。如果需要返回行索引 Dataframe ,可以使用reset_index

df2 = df.groupby(['Department', 'Status']).count().rename(columns={'Task':'Count'}).reset_index()

输出(针对示例数据):

Department    Status Count
0      Sales  Complete     1
1      Sales  Pendiing     1
2       Tech  Complete     2
3       Tech   Pending     1

如果需要,您可以在Status上过滤该内容:

df2[df2['Status'] == 'Complete']

输出:

Department    Status  Count
0      Sales  Complete      1
2       Tech  Complete      2
3htmauhk

3htmauhk2#

下面是使用pandas.GroupBy.count生成预期输出的替代方法

df = df[df['Status'] == 'Complete'].groupby('Department')['Task'].count().reset_index()
df.columns = ['Department', 'Count']

df['Status'] = 'Completed'
df = df.reindex(columns=['Department', 'Status', 'Count'])

print(df)
Department     Status  Count
0      Sales  Completed      1
1       Tech  Completed      2

相关问题