python - 如何在 python/pandas 中解压缩/解聚合分层数据?

标签 python pandas aggregate aggregation

我有一些压缩/聚合数据,例如

Incident_ID Case_ID_1   Name_1  Case_ID_2   Name_2  Common
1   1.1 Peter   1.2 Sally   Apple
2   2.1 Sam 2.2 Juliet  Banana

进入此

Incident_ID Case_ID Name    Common
1   1.1 Peter   Apple
1   1.2 Sally   Apple
2   1.1 Sam Banana
2   2.1 Juliet  Banana

我知道如何在 pandas 中聚合数据,但据我所知,我在网上找不到任何对此类数据进行反聚合的示例。

最佳答案

让我们尝试一下:

df1 = df.set_index(['Incident_ID','Common'])

df_case = df1[['Case_ID_1','Case_ID_2']].stack().reset_index(level=2,drop=True).rename('Case')

df_name = df1[['Name_1','Name_2']].stack().reset_index(level=2,drop=True).rename('Name')

df_out = pd.concat([df_case,df_name], axis=1).reset_index()

输出:

   Incident_ID  Common  Case_ID    Name
0            1   Apple      1.1   Peter
1            1   Apple      1.2   Sally
2            2  Banana      2.1     Sam
3            2  Banana      2.2  Juliet

关于python - 如何在 python/pandas 中解压缩/解聚合分层数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44507596/

相关文章:

python - Django - 在无效表单提交中保存字段

python - 如何将 python 从 UCS2 更改为 UCS4

domain-driven-design - 您使用什么方法来识别域驱动设计中的聚合根?

sql - "Running Product"PostgreSql 中的聚合/窗口函数?

python - Pandas 聚合然后得到组平均值

java - 字符串类内部 - 如果使用 UTF-8,缓存字符偏移到字节关系

python - 从字符串中拆分并删除整行

python - 访问 pandas 数据框中的列时出现问题

python - Pandas .at 与 .loc

python - pandas.to_datetime ValueError : cannot assemble the datetimes