python - 如何从数据框中将多个级别的聚合总和放入时间序列列中

标签 python pandas time-series hierarchy

我有一个 pandas 数据框,它具有各个层次级别的每月计数。它是长格式,我想转换为宽格式,每个聚合级别都有列。

其格式如下:

date | country | state | county | population 
01-01| cc1     | s1    | c1     | 5
01-01| cc1     | s1    | c2     | 4
01-01| cc1     | s2    | c1     | 10
01-01| cc1     | s2    | c2     | 11
02-01| cc1     | s1    | c1     | 6
02-01| cc1     | s1    | c2     | 5
02-01| cc1     | s2    | c1     | 11
02-01| cc1     | s2    | c2     | 12
.
.

现在我想将其转换为以下格式:

date | country_pop| s1_pop | s2_pop| .. | s1_c1_pop | s1_c2_pop| s2_c1_pop | s2_c2_pop|..

01-01| 30         | 9      | 21    | ...| 5         | 4        | 10         | 11        |..
02-01| 34         | 11     | 23    | ...| 6         | 5        | 11         | 12        |..
.
.

状态总数为,4,s1....s4。

每个州的县都可以标记为 c1...c10(有些州可能更少,我希望这些列为零。)

我想获得每个聚合级别的时间序列,按日期排序。我如何得到这个?

最佳答案

让我们使用带有 level 参数的 sum 和 pd.concat 将所有数据帧组合在一起。

#Aggregate to lowest level of detail
df_agg = df.groupby(['country', 'date', 'state', 'county'])[['population']].sum()

#Reshape dataframe and flatten multiindex column header
df_county = df_agg.unstack([-1, -2])
df_county.columns = [f'{s}_{c}_{p}' for p, c, s in df_county.columns]

#Sum to next level of detail and reshape
df_state = df_agg.sum(level=[0, 1, 2]).unstack()
df_state.columns = [f'{s}_{p}' for p, s in df_state.columns]

#Sum to country level 
df_country = df_agg.sum(level=[0, 1])

#pd.concat horizontally with axis=1
df_out = pd.concat([df_country, df_state, df_county], axis=1).reset_index()

输出:

  country   date  population  s1_population  s2_population  s1_c1_population  \
0     cc1  01-01          30              9             21                 5   
1     cc1  02-01          34             11             23                 6   

   s1_c2_population  s2_c1_population  s2_c2_population  
0                 4                10                11  
1                 5                11                12  

关于python - 如何从数据框中将多个级别的聚合总和放入时间序列列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57807358/

相关文章:

python - NLTK ConditionalFreqDist 到 Pandas 数据帧

python - 如何在 pandas 数据框中应用递归数字过滤器?

python - 将 TCL 脚本的输出记录到 Tkinter 文本小部件中

python - 使用什么过滤器可以消除角点对结果的影响

python - pyqt获取图像位置

r - 在数据框中输入附加行作为相邻现有行值之间的中点

python - 前向填充时间序列数据指定频率的某些列

python - 如果我们知道元素是唯一的,则可以快速扩展集合

python - 如何将填充应用于1?

python - Pandas Python : Slice/Transform URL to get item and item counts