pythonpandasindexing

pandas dataframe - return the value in iloc, or return zero if it does not exist


In using the iloc method for Pandas dataframe, I want to return zero if the value does not exist: (I have a query which it will always return either one row or an empty dataframe. I want the first left value when it exists)

import pandas as pd

mydict = {"col1":[1,2], "price":[1000,2000]}
df = pd.DataFrame(mydict)
query=df[df['price']>3000]

try:
    print(query.iloc[0][0])
except BaseException:
    print(0)

#print result: 0

Is there any better way or built-in method for iloc? I am thinking of something similar to the get method of Python dictionaries!


Solution

  • You can be more pythonic replacing your try/except block with:

    print(0 if len(query)==0 else query.iloc[0][0])

    Explanation: len() applied to a pandas Dataframe returns the number of rows.

    Update: as suggested in comments, query.empty this is more idiomatic and .iat is better for scalar lookups, hence:

    print(0 if query.empty else query.iat[0,0])