pythonpandasdataframekeyerror

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:

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"]