使用透视表生成的 Pandas DataFrame 进行绘图

7
我正在尝试使用Pandas在Jupyter Notebook中绘制一条折线图,比较特定州在1960-1962年间的谋杀率。
以下是我的现状和到达此处的方法的简要说明:
我正在使用一个犯罪csv文件,它看起来像这样:enter image description here 目前我只对三列感兴趣:州、年份和谋杀率。具体而言,我只对五个州感兴趣——阿拉斯加州、密歇根州、明尼苏达州、缅因州和威斯康星州。
因此,为了生成所需的表格,我执行了以下操作(仅显示前5行条目):
al_mi_mn_me_wi = crimes[(crimes['State'] == 'Alaska') | (crimes['State'] =='Michigan') | (crimes['State'] =='Minnesota') | (crimes['State'] =='Maine') | (crimes['State'] =='Wisconsin')]
control_df = al_mi_mn_me_wi[['State', 'Year', 'Murder Rate']]

enter image description here

从这里开始我使用了pivot函数

df = control_1960_to_1962.pivot(index = 'Year', columns = 'State',values= 'Murder Rate' ) 

enter image description here

我被卡在这里了。 在执行操作时出现了KeyError错误(错误为Year):

df.plot(x='Year', y='Murder Rate', kind='line')

尝试时只需

df.plot()

我得到了这个不稳定的图表。

enter image description here

我如何获得我想要的图表?

2个回答

8

给定一个长格式(整洁格式)的数据框,使用 pandas.DataFrame.pivot 转换成宽格式,然后可以直接用 pandas.DataFrame.plot 进行绘图。

python 3.8.11pandas 1.3.3matplotlib 3.4.3 中测试通过。

import numpy as np
import pandas as pd

control_1960_to_1962 = pd.DataFrame({
    'State': np.repeat(['Alaska', 'Maine', 'Michigan', 'Minnesota', 'Wisconsin'], 3),
    'Year': [1960, 1961, 1962]*5,
    'Murder Rate': [10.2, 11.5, 4.5, 1.7, 1.6, 1.4, 4.5, 4.1, 3.4, 1.2, 1.0, .9, 1.3, 1.6, .9]
})

df = control_1960_to_1962.pivot(index='Year', columns='State', values='Murder Rate')

# display(df)
State  Alaska  Maine  Michigan  Minnesota  Wisconsin
Year                                                
1960     10.2    1.7       4.5        1.2        1.3
1961     11.5    1.6       4.1        1.0        1.6
1962      4.5    1.4       3.4        0.9        0.9

绘图

您可以明确告诉Pandas(以及通过它实际执行绘图的matplotlib包)您想要的xticks:

ax = df.plot(xticks=df.index, ylabel='Murder Rate')

输出:

enter image description here

ax 是一个matplotlib.axes.Axes 对象,你可以通过它进行许多自定义操作来绘制图形。

下面是如何在 x 轴上绘制 States 的方法:

ax = df.T.plot(kind='bar', ylabel='Murder Rate')

输出:

在这里输入图片描述


(注:此内容已经是中文,无需再翻译)

3

尝试这个,你可以探索更多。

   pip install pivottablejs

   import pandas as pd
   import numpy as np
   from pivottablejs import pivot_ui
   df = pd.DataFrame({
      'State': np.repeat(['Alaska', 'Maine', 'Michigan', 'Minnesota','Wisconsin'], 3),
      'Year': [1960, 1961, 1962]*5,
      'Murder Rate': [10.2, 11.5, 4.5, 1.7, 1.6, 1.4, 4.5, 4.1, 3.4, 1.2, 1.0, .9, 1.3, 1.6, .9]})

使用pivot_ui(df)函数。

enter image description here


这看起来很有趣,你能告诉我更多关于这种情况下的细胞值1和2代表什么吗?编辑:这是指具有指定谋杀率的哪些州的计数吗? - Chumbawoo
这个项目已经四年没有更新了。使用前请注意查看,https://github.com/nicolaskruchten/pivottable - Isura Nimalasiri

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接