Skip to content
Advertisement

Python Pandas: How to get previous dates with a condition [closed]

I have dataset with the following columns:

  • encounterDate
  • FormName
  • PersonID

In the FormName, I have the following forms:

  1. Baseline
  2. Follow-up

Here’s a sample data:

JavaScript

I would like to have the following table:

JavaScript

How do I write this code in Python?

Additionally, I would like to also rank them:

JavaScript

Here’s my working code in SQL

JavaScript

Thank you in advance.

John

Advertisement

Answer

This would be fairly straight forward in pandas

It looks like you need to groupby both the PersonID and FormName to get the proper groupings. Within those groups you need to shift encounterDate and you need a cumulative count of the same.

cumcount starts at zero, so you may want to add 1 to the rank column to get the desired output.

JavaScript

Output

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement