有没有一种方法可以聚合行而不汇总它们的结果?

2024-05-19 18:19:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我的数据框由两列组成。一个有病人的身份证,一个有病人的问题。 我需要创建一个数据框,其中患者的所有问题都与相应的患者ID放在一行中。目前,如果患者有问题,此数据框将生成一个唯一的行

PAT_MRN_ID  Problem                      
9641956     Headache
9641956     Stomach_ache  
8227510     Headache 
8165474     Chicken_pox
7860000     Stomach_ache

上面的例子需要如下:

 PAT_MRN_ID  Headache         Stomach_ache      Chicken_pox
 9641956      1                1                   0
 8227510      1                0                   0
 8165474      0                0                   1
 7860000      0                1                   0

最后,我想将数据帧分类到上面的示例中。我尝试使用循环和聚合,但不幸的是,我的基本编程技能还不够


Tags: 数据患者idproblem身份证patchickenstomach
3条回答

^{}^{}、每个索引的最大值和^{}一起使用:

df1 = (pd.get_dummies(df.set_index('PAT_MRN_ID')['Problem'], 
                    prefix='', prefix_sep='')
         .max(axis=0, level=0)
         .reset_index())
print (df)

PAT_MRN_ID Chicken_pox  Headache  Stomach_ache                                  
9641956               0         1             1
8227510               0         1             0
8165474               1         0             0
7860000               0         0             1

使用pd.get\U假人

import pandas as pd
df = pd.DataFrame({"PAT_MRN_ID": [9641956, 9641956, 8227510, 8165474, 7860000], "Problem": ["Head", "Stomach", "Head", "Pox", "Stomach"]})
pd.get_dummies(df,columns=["Problem"]).groupby(df.index).sum()
                  Problem_Head  Problem_Pox  Problem_Stomach
PAT_MRN_ID                                            
7860000                0            0                1
8165474                0            1                0
8227510                1            0                0
9641956                1            0                1

首先得到“问题”的假人,然后分组

import pandas as pd
df = pd.DataFrame({ "PAT_MRN_ID" : [9641956,9641956,8227510,8165474,7860000],
                    "Problem" : ["Headache","Stomach-Ache","Headache","Chicken-Pox","Stomach-Ache"]
                 })

    PAT_MRN_ID  Problem
0   9641956     Headache
1   9641956     Stomach-Ache
2   8227510     Headache
3   8165474     Chicken-Pox
4   7860000     Stomach-Ache


df=pd.get_dummies(df, columns=['Problem'],prefix='',prefix_sep='')
     .groupby(['PAT_MRN_ID'], as_index=False)
     .max()


    PAT_MRN_ID  Chicken-Pox Headache    Stomach-Ache
0   7860000     0           0           1
1   8165474     1           0           0
2   8227510     0           1           0
3   9641956     0           1           1

相关问题 更多 >