pandas 数据帧 - 返回 iloc 中的值,如果不存在则返回零

Hos*_*ein 3 python indexing pandas

在对 Pandas 数据帧使用 iloc 方法时,如果值不存在,我想返回零:(我有一个查询,它总是返回一行或一个空数据帧。我想要第一个左值存在时)

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
Run Code Online (Sandbox Code Playgroud)

iloc 有没有更好的方法或内置方法?我在想类似getPython字典的方法!

Art*_*nov 5

你可以更 pythonic 替换你的 try/except 块:

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

说明:应用于熊猫数据帧的 len() 返回行数。

更新:正如评论中所建议的,query.empty这更惯用,.iat更适合标量查找,因此:

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