Pain is a prevalent consequence of cancer that may be associated with the progression of the disease. Understanding pain trajectory patterns can support end of life pain management, a crucial part of palliative care. This secondary data analysis study identifies 2 pain trajectory patterns 2 years before death- stable with mild pain, and elevating to moderate pain, by analyzing 989 deceased cancer patients' data from electronic health records using a longitudinal machine learning algorithm. Age at death, sex, comorbidities, bone cancer diagnosis, and receiving cancer treatments within 3 months before death were significant predictors of pain trajectories based on the decision tree, random forest, and logistic models. The findings of this study can inform timely patient and clinician communications to improve pain management and end-of-life palliative care plans.