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

How to make a function with if condition for pandas dataframe

I want to make a function that can append a new line of text to a .txt file with if condition.
I’m not good at code. Can someone explain to me how to create a function in python?

ex : given a table like this

text similarity polarity
ABCDD 0.6 POSITIF
ASDAS 0.4 NEGATIF
ASGAS 1.0 POSITIF

So , i want to make a function with if condition. The condition is like this :
If the value in column dataframe [‘similarity’] is greater than 0.5 , and the value in other column dataframe [‘polarity’] is "POSITIF". Then , i want to append a new line of text to a .txt file.
Can someone explain how to make that possible?
I’ve tried myself , but i guess it’s a total mess

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

if (df['similarity'] > 0.5) & df['polarity'].str.contains('POSITIF').any():
    with open("text.txt","a") as myfile:
        myfile.write("text appended \n")

>Solution :

It depends what you want to do exactly.

If you need to loop over all the rows, useiterrows (Warning, it is slow!):

with open("text.txt","a") as myfile:
    for key, row in df.iterrows():
        if (row['similarity'] > 0.5) and ('POSITIF' in row['polarity']):
            myfile.write("text appended \n")

If you want to append the line if any row matches both conditions:

if (df['similarity'].gt(0.5) & df['polarity'].str.contains('POSITIF')).any():
    with open("text.txt","a") as myfile:
        myfile.write("text appended \n")
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