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

Python: adding observations based on an index restart in pandas dataframe

I have a dataframe that looks like this:

df = pd.DataFrame({'index': [ 1, 2, 3, 4, 5, 6, 1, 2, 3, 4,5,6 ],
         'data': [  1.5, 0.22, 0.323, 4.4, 5.62, 0.56, 1.32, 2.1, 3.09, 4,5.3,0.6]})

I would like to have a new month when the index count starts again at 1. The month allocation does not follow a pattern, but I created a list that stores the months I want to have attributed to each restart of the count.

What I want is something like this dataframe:

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

months =["April", "June"]

df = pd.DataFrame({'index': [ 1, 2, 3, 4, 5, 6, 1, 2, 3, 4,5,6 ], 
          'data': [  1.5, 0.22, 0.323, 4.4, 5.62, 0.56, 1.32, 2.1, 3.09, 4,5.3,0.6],
         'Month': ['April', 'April', 'April', 'April', 'April', 'April', 'June', 'June', 'June', 'June', 'June', 'June'] })

>Solution :

you can iterate over the index column:

import pandas as pd

df = pd.DataFrame({'index': [ 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6 ],
                   'data': [ 1.5, 0.22, 0.323, 4.4, 5.62, 0.56, 1.32, 2.1, 3.09, 4, 5.3, 0.6]})

months = ["April", "June"]
month_index = 0
month_dict = {}

for i in range(len(df)):
    if df.loc[i, 'index'] == 1:
        month_index = (month_index + 1) % len(months)
        month_dict[1] = months[month_index]
    month_dict[df.loc[i, 'index']] = months[month_index]

df['Month'] = df['index'].map(month_dict)

print(df)
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