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!
fillnato replace missing values with 0?fillna(0)will never work, this is about what happens whenqueryis an empty dataframe. Filling null in an empty dataframe with0will have no impact.