在第三维上绘制一个pandas panel colum

时间:2018-04-27 14:45:59

标签: pandas matplotlib

我有3个具有相同形状且具有以下数据的独立数据帧。

# for 2015
Grave Crimes    Cases Recorded  Mistake of Law fact
Abduction       725             3
Kidnapping      246             6
Arson           466             1
Mischief        436             1
House Breaking  12707           21
Grievous Hurt   1299            3

# for 2016
Grave Crimes    Cases Recorded  Mistake of Law fact
Abduction       738             4
Kidnapping      297             9
Arson           486             4
Mischief        394             1
House Breaking  10287           14
Grievous Hurt   1205            0

# for 2017
Grave Crimes    Cases Recorded  Mistake of Law fact
Abduction       647             2
Kidnapping      251             10
Arson           418             3
Mischief        424             0
House Breaking  8913            12
Grievous Hurt   1075            1

我希望按年度对每个专栏(例如“案例记录”)与“严重犯罪”类型组进行比较。我目前的小组如下。创建面板时我没有设置任何索引。此外,每个数据框都没有任何列表示上面显示的年份。

pnl = pd.Panel({2015: df15, 2016: df16, 2017: df17})

我的预期输出如下所示。有人可以帮我吗?

enter image description here

1 个答案:

答案 0 :(得分:0)

Pandas在0.20.1 +

中弃用了小组

我们可以使用带有键的pd.concat将这些数据帧组合成一个数据帧,然后使用重塑和pandas图。

l = ['df2015','df2016','df2017']
df_out = pd.concat([eval(i) for i in l], keys=l)\
           .set_index('Grave Crimes',append=True)['Cases Recorded'].unstack(0)\
           .rename(columns=lambda x: x[2:]).reset_index(0, drop=True)

df_out.plot.bar()

输出:

enter image description here