Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python/Pandas中处理许多不同类型的valueError结果?_Python_Pandas_Try Except_Valueerror - Fatal编程技术网

如何在Python/Pandas中处理许多不同类型的valueError结果?

如何在Python/Pandas中处理许多不同类型的valueError结果?,python,pandas,try-except,valueerror,Python,Pandas,Try Except,Valueerror,我试图从一个输入中提取一个值,这个值是脏的,有很多可能 输入是一个具有多种可能类型的系列,例如:“8673331000”、“8673331000”、“8673331000”、8673331000、18673331000、8673331000.0、NaN、“867B31000” 在前5个案例中,我正在寻找867333,采用int格式。我想报告的最后两个案例未知或类似情况 我一直在使用try/except,但是有许多不同类型的ValueError报告 现在我正在使用: *try: val =

我试图从一个输入中提取一个值,这个值是
脏的
,有很多可能

输入是一个具有多种可能类型的系列,例如:
“8673331000”、“8673331000”、“8673331000”、8673331000、18673331000、8673331000.0、NaN、“867B31000”

在前5个案例中,我正在寻找
867333
,采用
int
格式。我想报告的最后两个案例
未知
或类似情况

我一直在使用try/except,但是有许多不同类型的
ValueError
报告

现在我正在使用:

*try:
    val = int(number)
except ValueError as ve:
    if (number[len(number)-1]=="'"):
        val = int(number[0:len(number)-2])
    else:
        val = int(float(number))*
except
子句处理输入只有一个引号的情况,但不处理
NaN
情况


谢谢您的想法。

如果输入已经是pandas系列,您可以使用
pandas.to\u numeric(您的\u系列\u数据,errors='concurve')。fillna(-9999)。astype(int)

您可以直接使用此系列的值,而不必使用try/except将它们强制为整数

在pandas中,整数不能表示为NaN,因此在本例中,它们被替换为-9999。当您从序列中提取值时,如果它与-9999匹配,您可以将其设置为“无”,或者为缺少的值设置代码应该具有的任何值

如果您的输入值是字符串,它们可能被强制为NaN而不是整数,例如

data=StringIO('''Values
,8673331000
,"8673331000"
,\'8673331000\'
,18673331000
,8673331000.0
,NaN
,867B331000
''')
df = pd.read_csv(data, sep=",")
当使用
pd.to_numeric(df.iloc[:,0],errors='improve').fillna(-9999).astype(int)
时,第三个值将以NaN结尾。在这种情况下,我建议从输入数据中删除所有“或”


希望能有所帮助!

最后,我决定使用正则表达式创建一个精心设计的if/elif子句。我怀疑嵌套的try/except会起作用。但是,考虑到valueError可能由许多不同的可能性导致,我坚持使用前者

这里是我登陆的地方,为了简单起见做了一些编辑

def get_代码(输入,记录器): #获取原始输入的整数形式,该形式可以是 #整数、浮点、字符串(例如8673341000、18673341000、“8673341000”, #“8673341000”,“8673341000”,“867BBA1000”,8673341000.0,南 #如果提供了难以辨认的输入,则返回“未知”

import re
import math
import numpy as np

val = "Unknown"

if (type(input)==int):
    val = input

elif(type(input)==float):
    #could be NaN or a float (e.g. 100.0, but not 1.0e+10)
    try:
        val= int(input)
    except:
        val="Unknown"

elif(type(input)==str):
    if (input[len(input)-1]=="'"):
        val = int(input[0:len(input)-1])
    elif (re.match('^[0-9]+$', input)):
        #input contains only digits
        val = int(input)
    elif ((re.match('\s+\d+\s+', input)) or (re.match('\s+\d+', input)) or (re.match('\d+\s+', input))):
        #leading or trailing spaces
        input = input.strip()
        val=int(input)
    else:
        return "Unknown"
elif(type(np.float64(input).item())==float):
    #Input is of the form 1.416441e+10

    val = int(input)


else:
    logger.warning("Unknown Input type for get_NPANXX() ... input:" , input)
    logger.warning(type(input))
    return val #E.g. "Unknown Input"

#...more processing once val is in integer form
return

您是说要为不同的异常添加另一个
except
子句吗?只需添加另一个
except
子句,就像
ValueError
子句一样。或者您可以将
else
子句添加到
try
stmt中,请参阅
import re
import math
import numpy as np

val = "Unknown"

if (type(input)==int):
    val = input

elif(type(input)==float):
    #could be NaN or a float (e.g. 100.0, but not 1.0e+10)
    try:
        val= int(input)
    except:
        val="Unknown"

elif(type(input)==str):
    if (input[len(input)-1]=="'"):
        val = int(input[0:len(input)-1])
    elif (re.match('^[0-9]+$', input)):
        #input contains only digits
        val = int(input)
    elif ((re.match('\s+\d+\s+', input)) or (re.match('\s+\d+', input)) or (re.match('\d+\s+', input))):
        #leading or trailing spaces
        input = input.strip()
        val=int(input)
    else:
        return "Unknown"
elif(type(np.float64(input).item())==float):
    #Input is of the form 1.416441e+10

    val = int(input)


else:
    logger.warning("Unknown Input type for get_NPANXX() ... input:" , input)
    logger.warning(type(input))
    return val #E.g. "Unknown Input"

#...more processing once val is in integer form
return