gpt4 book ai didi

python - 从数据透视表绘制 Pandas DataFrame

转载 作者:行者123 更新时间:2023-12-02 11:47:10 26 4
gpt4 key购买 nike

我正在尝试使用 Jupyter Notebook 中的 Pandas 绘制线图,比较 1960-1962 年特定州的谋杀率。

关于我现在在哪里以及我如何到达这里的一些背景:

我正在使用犯罪 csv 文件,如下所示: enter image description here

我暂时只对 3 列感兴趣:州、年份和谋杀率。具体来说,我只对 5 个州感兴趣 - 阿拉斯加州、密歇根州、明尼苏达州、缅因州、威斯康星州。

为了生成所需的表格,我这样做了(仅显示前 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 (KeyError was Year):

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

当尝试时

df.plot()

我得到了这个奇怪的图表。

enter image description here

如何获得我想要的图表?

最佳答案

给定一个长(整齐)格式的数据帧,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

axmatplotlib.axes.Axes object ,并且您可以通过它对您的绘图进行很多很多自定义。

以下是如何在 x 轴上使用 States 进行绘图:

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

输出:

enter image description here

关于python - 从数据透视表绘制 Pandas DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53811565/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com