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

Looping through dataframe with conditions

This is my input data, which is stored in dataframe df.
Input

Now i want to change all the values in column B to Yearly format. Here is my code:

D = []
for i in df['B']:
    for j in df['C']:
        if j == 'Year':
            D.append(int(i)/1) 
        elif j == 'Month':
            D.append(int(i)/12)
        elif j == 'Day':
            D.append(int(i)/365)

print(len(df))
print(len(D))

While my original df only has len of 10, the output (list D) has len of 100. Anyone knows how to fix the issue here?

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

>Solution :

You can try with map

df['D'] = df['B'].div(df['C'].map({'Year':1, 'Month':12, 'Day':365})
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