首页 > 解决方案 > 让 Pandas `df.get()` 无论列键还是行键不正确都表现得优雅

问题描述

我有一个 Pandas 数据框和一个从数据框中提取条目的函数。如果请求的条目不存在于数据框中——无论是因为请求的列不存在,还是因为请求的行/索引不存在,或者两者兼而有之——我想返回字符串'entry not found'而不是错误消息。

import pandas as pd

df = pd.DataFrame({'col1': [12, 13, 14, 15], 'col2': [16, 15, 14, 13]})

理想情况下,我想将我的查询函数编写为

def query(col, idx):
    return df.get(col, idx, 'entry not found')

不幸的是,该df.get()方法只接受两个参数,所以我想出了以下替代方案。

    def query1(col, idx):
        return df[col, idx]
    
    def query2(col, idx):
        return df[col].get(idx, 'entry not found')
    
    def query3(col, idx):
        return df.get(col, 'entry not found')[idx]
    
    def query4(col, idx):
        return df.get(col, 'entry not found').get(idx, 'entry not found')

仅当用户请求不存在的行时才起作用query2query4

# User asks for a row that doesn't exist.
query1('col1', 24) # KeyError
query2('col1', 24) # 'entry not found'
query3('col1', 24) # ValueError: 24 is not in range
query4('col1', 24) # 'entry not found'

而只有query3(某种)在用户请求不存在的列时才有效:

# User asks for a column that doesn't exist.
query1('col5', 3) # KeyError
query2('col5', 3) # KeyError
query3('col5', 3) # Returns 'r' ( = 4th char of 'entry not found')
query4('col5', 3) # AttributeError: 'str' object has no attribute 'get'

如何获得所需的行为?有没有办法在没有沉重try: ... except: ...障碍的情况下做到这一点?

标签: pythonpandas

解决方案


您可以连接两个get(),用于数据框和返回的系列,默认值为空系列和错误消息

def query(col, idx):
    return df.get(col, pd.Series()).get(idx, 'entry not found')

print(query('col1', 0)) # 12
print(query('col1', 10)) # entry not found
print(query('col5', 0)) # entry not found
print(query('col5', 10)) # entry not found

推荐阅读