- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有 12 个相同形状的数据框,用于 12 年的数据收集。我需要使用它作为面板来绘制时间序列轴(年)上的各个列值。因此,我认为我应该将这些框架对齐为面板。
一些示例数据:
# 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
最佳答案
虽然面板允许添加维度,但分层索引是更常见的替代方案。例如,来自Python Data Science Handbook :
While Pandas does provide Panel and Panel4D objects that natively handle three-dimensional and four-dimensional data (see Aside: Panel Data), a far more common pattern in practice is to make use of hierarchical indexing (also known as multi-indexing) to incorporate multiple index levels within a single index. In this way, higher-dimensional data can be compactly represented within the familiar one-dimensional Series and two-dimensional DataFrame objects.
就你的情况
I have 12 dataframes of the same shape for 12 years of data collection. I need to use this as a panel to to plot the various column values across the time series axis (years).
假设您的 DataFrame 位于 df_2015
、df_2016
和 df_2017
中。您可以执行以下操作:
df_2015['year'] = 2015
df_2016['year'] = 2016
df_2017['year'] = 2017
df = pd.concat([df_2015, df_2016, df_2017]).set_index(['Grave Crimes', 'year'])
例如,现在要获取“Abduction”的所有年份的数据
,请使用
df[df.index.get_level_values(0) == 'Abduction']
关于python - 将 pandas 数据框对齐为面板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50055457/
我是一名优秀的程序员,十分优秀!