查找发生错误的位置

To find the location at which error has occured

我需要对范围进行数据验证。要检查列值是否在给定范围内,如果值大于或小于给定范围,则应该发生错误,并显示发生错误的行号或索引。

我的数据如下:

Draft_Fore 12 14 87 16 90

它应该会产生值 87 和 90 的错误,因为我认为列的范围必须大于 5 且小于 20。

我试过的代码如下:

def validate_rating(Draft_Fore):
    Draft_Fore = int(Draft_Fore)
    if Draft_Fore > 5 and Draft_Fore <= 20:
       return True
    return False
df = pd.read_csv("/home/anu/Desktop/dr.csv")
for i, Draft_Fore in enumerate(df):
try:
    validate_rating(Draft_Fore)
except Exception as e: 
    print('Error at index {}: {!r}'.format(i, Draft_Fore))
    print(e)

打印行中发生错误的位置

澄清我的评论的一点解释。假设你的 dataframe 看起来像

df = pd.DataFrame({'col1': [12, 14, 87, 16, 90]})

你可以

def check_in_range(v, lower_lim, upper_lim):
    if lower_lim < v <= upper_lim:
       return True
    return False

lower_lim, upper_lim = 5, 20
for i, v in enumerate(df['col1']):
    if not check_in_range(v, lower_lim, upper_lim):
        print(f"value {v} at index {i} is out of range!")

# --> gives you
value 87 at index 2 is out of range!
value 90 at index 4 is out of range!

所以你的校验功能基本没问题。但是,如果您调用 enumerate a df,值将是列名。你需要的是枚举具体的列。

关于您提出异常的想法,我建议您查看 raise and assert

所以你可以,例如使用 raise:

for i, v in enumerate(df['col1']):
    if not check_in_range(v, lower_lim, upper_lim):
        raise ValueError(f"value {v} at index {i} is out of range")

# --> gives you
ValueError: value 87 at index 2 is out of range

assert:

for i, v in enumerate(df['col1']):
    assert v > lower_lim and v <= upper_lim, f"value {v} at index {i} is out of range"

# --> gives you
AssertionError: value 87 at index 2 is out of range

注意:如果你有df,为什么不使用它的功能来方便呢?要获取该列的 范围内 值,您只需执行

df[(df['col1'] > lower_lim) & (df['col1'] <= upper_lim)]

# --> gives you
   col1
0    12
1    14
3    16