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

Appending list with highest value from two columns using for loop in pandas

I have two columns: column A, and column B.

I would like to find whether the value in each row of column A is larger than the value for the same row in column B, and if it is append a list with these values.

I’m able to append the list if the value in column A is higher than a set value, but I’m unsure how to compare it to the value from column B.

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

The below code appends the list if the value in column A is higher than 4. Hopefully I’m on the right track and can just substitute 4 with some other code?

list = []

for x in A:
    if x > 4:
        list.append(x)

print(list)

Any help would be greatly appreciated.

Thank you!

>Solution :

An approach could be:

import pandas as pd

df = pd.DataFrame({"A":[2, 3, 4, 5], "B":[1, 4, 6, 3]}) # Test DataFrame

print(list(df[df["A"] > df["B"]]["A"]))

OUTPUT

[2, 5]
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