如何在数据帧中加入索引的公共元素?

2024-06-16 09:37:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个数据帧:

           type count
batsman         
V Kohli     4   361
V Kohli     6   149
SK Raina    5   1
SK Raina    6   161
RG Sharma   5   1
RG Sharma   6   164

现在我们可以看到索引中有commmon条目。我想绘制一个barh图,所以我想把索引合并成一个,这样数据帧看起来像这样:

            type count
batsman         
V Kohli     4   361
            6   149
SK Raina    5   1
            6   161
RG Sharma   5   1
            6   164

我该怎么做?你知道吗


Tags: 数据typecount绘制条目rgskcommmon
2条回答

您可以将索引分配给一个新列并执行groupby。你知道吗

df['batsman'] = df.index
grouped_df = df.groupby(['batsman', 'type']).agg({'count': 'sum'})
# grouped_df

           type count
batsman         
V Kohli     4   361
            6   149
SK Raina    5   1
            6   161
RG Sharma   5   1
            6   164

您可以^{}您的数据帧的索引和“type”列,然后在barh图中聚合以获得合理的分组输出。你知道吗

df.groupby([df.index,'type'])['count'].sum().plot.barh(title='Counts')

enter image description here

相关问题 更多 >