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

Discussão em 'Python' iniciado por Stack, Fevereiro 14, 2025.

  1. Stack

    Stack Membro Participativo

    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!

    Continue reading...

Compartilhe esta Página