【问题标题】:To find the location at which error has occured查找发生错误的位置
【发布时间】:2020-02-03 23:00:14
【问题描述】:

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

我的数据如下:

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)

打印行中发生错误的位置

【问题讨论】:

  • 请检查您的代码的缩进,它似乎不正确。然后,您的函数不会引发错误,它只会返回 True 或 False ...您可以使用它,例如if not validate_rating(Draft_Fore):,然后打印消息。
  • 我已经更正了我的代码的意图,但 for 循环没有正确迭代@MrFuppes

标签: python-3.x for-loop exception try-catch python-3.6


【解决方案1】:

稍微解释一下以澄清我的评论。假设您的 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!

所以你的检查功能基本没问题。但是,如果您调用enumeratedf,则值将是列名。您需要的是枚举特定列。

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

所以你可以例如使用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,为什么不使用它的功能来方便呢?要获取列的 in-range 值,您可以这样做

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

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

【讨论】:

    猜你喜欢
    • 2014-09-26
    • 1970-01-01
    • 2015-03-11
    • 2014-10-11
    • 2014-01-07
    • 1970-01-01
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    相关资源
    最近更新 更多