python - 如何使用熊猫计算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)
好吧,在我运行之后,内核永远不会停止,我只是学会了自己编程,因此我不知道发生了什么,所以我不得不终止内核。有人可以帮我弄这个吗?
解决方案
您可以将数据框中的“是”替换为 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()
推荐阅读
- javascript - 在 React 中开发期间和部署后的不同图像行为
- python - 警告:此 shell 正在您的本地机器上运行,在 WSL 中使用 VS Code 进行 python 脚本调试
- c# - 如何将 xUnit 覆盖率报告上传到 Codecov?
- ruamel.yaml - 遇到 TypeError:在 ruamel.yaml.comments import CommentedMap 上调用更新时,'int' 对象不可下标
- html - HTML 输入表单到外部链接
- node.js - Artillery.io js 测试?
- c - 打开使用 C 编写的文件时权限被拒绝
- java - 使用枚举更新工作项状态或创建用于更新工作项状态的特定方法
- javascript - 如何从 fetch 中获取 uri?
- android - 使用 Dialogflow 和 Flutter 导航到路由时出现问题