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

Creating multiple datetime columns for every request per PersonID Python

My dataset consists out of two columns, PersonID and Request for application(Aanvraag datum). Some PersonIDs occur multiple times because these persons received multiple request on different dates:

enter image description here

Now I want to create multiple request columns per PersonID. For example if a PersonID occurs three times, then the code creates three columns for three different requests dates. If a PersonID occurs one time, the code assigns NaN to the empty requests. In the end there will be as many columns as the PersonID with the most requests.

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

Example:
enter image description here

Many thanks!

>Solution :

Use GroupBy.cumcount with DataFrame.set_index and append=True and then Series.unstack with DataFrame.add_prefix:

df1 = (df.set_index(df.groupby(level=0).cumcount().add(1), append=True)['Aanvraag datum']
        .unstack()
        .add_prefix('Aanvraag '))
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