Skip to content

Instantly share code, notes, and snippets.

@fschwar4
Last active January 25, 2025 10:45
Show Gist options
  • Save fschwar4/1cd7d2b68c70ca068ce38ebd067cdcaf to your computer and use it in GitHub Desktop.
Save fschwar4/1cd7d2b68c70ca068ce38ebd067cdcaf to your computer and use it in GitHub Desktop.
lab value transformations
import pandas as pd
## CALCIUM CORRECTION (based on Albumin)
# cave: check the units of Calcium and Albumin
# Calcium is given in mmol/l; Albumin in g/l
# equation following Payne 1973; https://doi.org/10.1136/bmj.4.5893.643
# Adjusted calcium = calcium - albumin + 4.0 (if albumin in g/dL and calcium in mg/dL)
# Calcium conversions: 1 mg/dL = 0.25 mmol/L; 1 mmol/L = 4 mg/dL
# Calcium corrected [mmol/l] = Calcium measured [mmol/l] – (0,025 x Albumin [g/l]) + 1
# Create a DataFrame with dummy data for 'Calcium (P)' and 'Albumin (P)'
dummy_data = {
'Calcium (P)': [2.1, 2.3, 2.2, 2.4, 2.5],
'Albumin (P)': [40, 42, 38, 41, 39]
}
df = pd.DataFrame(dummy_data)
df['Calcium (P), corrected'] = df['Calcium (P)'] - (0.025 * df['Albumin (P)']) + 1
df
# Calculate the eGFR using the CKD-EPI formula without race
# Reference: https://www.nejm.org/doi/10.1056/NEJMoa2102953
# 2021 CKD-EPI Creatinine = 142 x (Scr/A)^B x 0.9938^age x (1.012 if female)
# where A and B are the following:
# A = 0.7 for females, 0.9 for males
# B = -0.241 for females if Scr <= 0.7, -1.2 if Scr > 0.7
# B = -0.302 for males if Scr <= 0.9, -1.2 if Scr > 0.9
# cave: the eGFR is normalized to a height of 173 cm -> could be useful to normalize the height of the patients
# Serum creatinine: 1 mg/dL = 88.4 µmol/L; 1µmol/L = 0.011312217194570135 mg/dL
# Example DataFrame to test the code
data = {
'sex': ['male', 'female', 'male', 'female'],
'age': [45, 50, 60, 70],
'Kreatinin (P)': [1.0, 0.6, 1.2, 0.8],
'height': [173, 168, 180, 165] # Height in cm
}
df = pd.DataFrame(data)
data_p = pd.DataFrame({'age': [45, 50, 60, 70], 'sex': ['male', 'female', 'male', 'female']})
# Determine gender-specific constants
is_female = (df['sex'] == 'female').values
A = np.where(is_female, 0.7, 0.9)
B = np.where(is_female, -0.241, -0.302)
# Adjust B based on creatinine levels
creatinine = df['Kreatinin (P)']
B = np.where(creatinine > A, -1.2, B)
# Calculate the correction factor for females
female_correction = np.where(is_female, 1.012, 1)
# Normalize height (assuming height is in cm)
if 'height' in df.columns:
height_normalization = df['height'] / 173 # Normalizing by an average height of 173 cm
else:
height_normalization = 1
# Calculate eGFR
df['eGFR (CKD-EPI 2021)'] = 142 * (creatinine / A) ** B * 0.9938 ** data_p['age'] * female_correction * height_normalization
df
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment