Python 来自数据框 groupby 的条形图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40313727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:23:20  来源:igfitidea点击:

Bar graph from dataframe groupby

pythonpandasggplot2pandas-groupby

提问by jhaywoo8

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.read_csv("arrests.csv")
df = df.replace(np.nan,0)
df = df.groupby(['home_team'])['arrests'].mean()

I'm trying to create a bar graph for dataframe. Under home_team are a bunch of team names. Under arrests are a number of arrests at each date. I've basically grouped the data by teams with the average arrests for that team. I'm trying to create a bar graph for this but am not sure how to proceed since one column doesn't have a header.

我正在尝试为数据框创建条形图。home_team 下是一堆队名。被捕人数是指每个日期的逮捕人数。我基本上按团队对数据进行了分组,该团队的平均逮捕人数。我正在尝试为此创建一个条形图,但我不确定如何继续,因为一列没有标题。

Data

数据

回答by piRSquared

copying data from your link and running df = pd.read_clipboard()

从您的链接复制数据并运行 df = pd.read_clipboard()

then using your code

然后使用你的代码

df = df.replace(np.nan,0)
df = df.groupby(['home_team'])['arrests'].mean()

df.plot.bar()

enter image description here

在此处输入图片说明

回答by loveR

Good one by @piRSuared, and I just buitified his answer :)

@piRSuared 写的很好,我刚刚给出了他的答案:)

## referenced to the answer by @piRSquared
df = df.replace(np.nan,0)
df = df.groupby(['home_team'])['arrests'].mean()

ax = df.plot(kind='bar', figsize=(10,6), color="indigo", fontsize=13);
ax.set_alpha(0.8)
ax.set_title("My Bar Plot", fontsize=22)
ax.set_ylabel("Some Heading on Y-Axis", fontsize=15);
plt.show()