gpt4 book ai didi

python - 将 pandas 数据框对齐为面板

转载 作者:行者123 更新时间:2023-12-01 01:57:00 25 4
gpt4 key购买 nike

我有 12 个相同形状的数据框,用于 12 年的数据收集。我需要使用它作为面板来绘制时间序列轴(年)上的各个列值。因此,我认为我应该将这些框架对齐为面板。

  1. 有人可以帮助我了解如何将数据框对齐为面板吗?
  2. 这是准备沿第三维绘图的正确方法吗?

enter image description here

一些示例数据:

# 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_2015df_2016df_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/

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