python - 让 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')
仅当用户请求不存在的行时才起作用query2
:query4
# 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: ...
障碍的情况下做到这一点?
解决方案
您可以连接两个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
推荐阅读
- aws-lambda - Lambda/NodeJS 调试器不使用 Cloud9/AWS SAM 环境变量
- python-3.x - 从 pandas xlsxwriter 打开 Excel (XLSX) 文件时出错
- c - 这里的“tempPtr”不是多余的吗?(链接列表)
- java - 无法在 Spring Boot Maven 项目中集成外部 jar
- flutter - 如何在 Flutter 中制作具有浮雕效果的按钮
- c++ - 使用 mem_fn 代替 mem_fun
- django - Heroku 应用程序在使用新依赖项推送更改后崩溃
- javascript - 以编程方式替换整个文档的“innerHTML”不会触发加载 JS?
- html - 我想将复选框标签向左移动
- javascript - async 标签是否用 Promise 包装了 JavaScript 函数?