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 pandas if for

I have a CSV file with many columns in it. Let me give you people an example.

A B C D 
1 1 0  
1 1 1 
0 0 0

I want to do this.

if col-A first row value == 1 AND col-B first row value == 1 AND col-C first row value == 1;
        then put "FIC" in first row of Col-D
   else:
        enter "PI"

I am using pandas.

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

There are more than 1500 rows and I want to do this for every row. How can I do this? Please help

>Solution :

If need test if all values are 1 per filtered columns use:

df['D'] = np.where(df[['A','B','C']].eq(1).all(axis=1), 'FIC','PI')

Or if only 0,1 values in filtered columns:

df['D'] = np.where(df[['A','B','C']].all(axis=1), 'FIC','PI')

EDIT:

m1 = df[['A','B','C']].all(axis=1)
m2 = df[['A','B','C']].isna().any(axis=1)
df['D'] = np.select([m1, m2], ['FIC', 'ZD'],'PI')
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