首页 > 解决方案 > 如何使用熊猫计算excel中特定文本的出现次数

问题描述

第一次来这里,刚开始学习编码,我正在对疾病的一些风险因素进行临床研究,在这里我已经获得了患者数据的优势。代码的目的是统计每个患者(每一行)的危险因素(肥胖、高血压、糖尿病、高脂血症)的数量,并将结果打印在一个新的列中,最后一步,统计有多少个患者总共有 4 个危险因素,有多少有 3 个,有 2 个,只有一个,或者没有。

日期框架是这样的(只是一个例子,不破坏机密性): 数据框的一部分

好吧,在python中尝试这部分,刚刚弥补,我尝试了以下代码:

import pandas as pd
df1=pd.DataFrame({'gender':['male','male','female','female','male'],'age':[49,60,65,20,65],
                  'obesity':['yes','yes','NaN','NaN','yes'],
                  'hypertension':['yes','yes','yes','NaN','yes'],
                  'diabetes':['NaN','yes','NaN','NaN','yes'],
                  'hyperlipidemia':['yes','yes','yes','NaN','NaN']})
factor_count=[] #to be written in the very right column
row=0
column=3
while row<=5:             #5 rows in total for this example
    count=0               #to count the risk factors of each row
    while column<=5:
        if df.iloc[row,column] == 'yes':         #probably my while loop is really stupid
            count+=1
            column+=1
    factor_count.append(count)
    row+=1
print(factor_count)

好吧,在我运行之后,内核永远不会停止,我只是学会了自己编程,因此我不知道发生了什么,所以我不得不终止内核。有人可以帮我弄这个吗?

标签: pythonexcelpandasmedical

解决方案


您可以将数据框中的“是”替换为 1,然后使用方法 sum:

df1.replace('yes',1,inplace=True)
df1.iloc[:,[2,3,4,5]] = df1.iloc[:,[2,3,4,5]].astype(float)
df1["Numbers of factor"] = df1.iloc[:,[2,3,4,5]].sum(axis=1)

然后这个列的直方图应该给出有多少患者有 1,2 3 ... 风险

df1["Numbers of factor"].hist()

推荐阅读