gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:48:36 25 4
gpt4 key购买 nike

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

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/

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