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

Pandas First Value That Doesnt Return KeyError

I have a dataframe that has either column A or B

I was hoping for a syntax that uses the or operator to have a stntax like:

Value = df.at['Total','A'] or df.at['Total','B']

but I still receive a KeyError exception. Is there a shorthand way to achieve this instead of doing something like:

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 'A' in df.columns:
    Value = df.at['Total','A']
else:
    Value = df.at['Total','B']

>Solution :

I would use ternary conditional operator:

df.at["Total", "B" if "B" in df else "A"]
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