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

Replacing a value with actual if condition with DataFrame in Python

I need help with implementing actual if conditions with dataframe. I know the replace and where functions, but unfortunately I am not directly able to use them.

Basically I want to change value of a column based on whether a folder exists with a UID. If the folder exists in related directory I want to place yes, if not, I want to place no. For example: if D:\data\folder\00010002 exists, then folder value of the UID should be yes. Else, it should be no. How can I do that?

import os
import pandas as pd

d = {'UID': ["00010002", "00010004"], 'folder': ['a', 'a']}
df = pd.DataFrame(data=d)

for a in d['UID']:
    if os.path.isdir(f'D:\data\folder\{a}'):
        df.loc[df.folder] == 'yes'
    else:
        df.loc[df.folder] == 'no'

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 :

Try this:

df['folder'] = df['UID'].apply(lambda uid: 'yes' if os.path.isdir(f'D:\\data\\folder\\{uid}') else 'no')
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