Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Fill NaN values of selected dataframe columns using For loop

I have a dataframe of patients Vital signs (HR, O2Sat, Temp, SBP, DBP, Resp) with NaN values. I filled NaN in individual patient based on Patient ID (P_ID) column using the code:

m['HR'] = m['HR'].fillna(m.groupby('P_ID')['HR'].transform('mean'))
m['O2Sat'] = m['O2Sat'].fillna(m.groupby('P_ID')['O2Sat'].transform('mean'))
m['Temp'] = m['Temp'].fillna(m.groupby('P_ID')['Temp'].transform('mean'))
m['SBP'] = m['SBP'].fillna(m.groupby('P_ID')['SBP'].transform('mean'))
m['DBP'] = m['DBP'].fillna(m.groupby('P_ID')['DBP'].transform('mean'))
m['Resp'] = m['Resp'].fillna(m.groupby('P_ID')['Resp'].transform('mean'))

It worked perfectly. However it is a lot of code. Is there anyway I use for loop to fill NaN values in only the vital columns? As there are some more columns without NaN values. Thanks.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Yes, you can use a loop

for i in ['HR','O2Sat','Temp','SBP','DBP','Resp']:
    m[i] = m[i].fillna(m.groupby('P_ID')[i].transform('mean'))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading