Python 如何忽略pandas.to_numeric()中的错误并将str更改为int
我收到pandas.to_numeric()的意外响应。 如果我用数字Python 如何忽略pandas.to_numeric()中的错误并将str更改为int,python,python-3.x,pandas,Python,Python 3.x,Pandas,我收到pandas.to_numeric()的意外响应。 如果我用数字 a=pd.系列(['1','2','3',np.nan]) b=pd.to_numeric(a,downcast='integer',errors='ignore') 打印([为b中的每个输入(每个)]) 回答是:[float,float,float,float] 但是如果我有真实的str序列,比如 a=pd.系列(['1','2','3',np.nan',a']) b=pd.to_numeric(a,downcast='
a=pd.系列(['1','2','3',np.nan])
b=pd.to_numeric(a,downcast='integer',errors='ignore')
打印([为b中的每个输入(每个)])
回答是:[float,float,float,float]
但是如果我有真实的str序列,比如
a=pd.系列(['1','2','3',np.nan',a'])
b=pd.to_numeric(a,downcast='integer',errors='ignore')
打印([为b中的每个输入(每个)])
它返回[str,str,str,float,str]
医生说:
如果“忽略”,则无效解析将返回输入
我认为无效解析只是“a”,所以我应该得到:[float,float,float,float,str]
问题是如何修复它并获得
[float,float,float,float,str]
一个可能的解决方案是使用errors='concurve'
将缺少的值替换为原始值-因此最后一个a
在final系列中:
a = pd.Series(['1', '2', '3', np.nan, 'a'])
b = pd.to_numeric(a, errors='coerce').fillna(a)
print([type(each) for each in b])
[<class 'float'>, <class 'float'>, <class 'float'>, <class 'float'>, <class 'str'>]
如果可能,字符串表示形式中带浮点数的整数:
a = pd.Series(['1', '2', '3.3', np.nan, 'a'])
def func(x):
try:
return int(x)
except Exception:
try:
return float(x)
except Exception:
return x
b = a.apply(func)
print([type(each) for each in b])
[<class 'int'>, <class 'int'>, <class 'float'>, <class 'float'>, <class 'str'>]
a=pd.系列(['1','2','3.3',np.nan',a'])
def func(x):
尝试:
返回整数(x)
除例外情况外:
尝试:
返回浮动(x)
除例外情况外:
返回x
b=a.apply(func)
打印([为b中的每个输入(每个)])
[, , ]
您也可以使用应用
:
print(a.apply(lambda x: float(x) if str(x).isdigit() else x))
输出:
0 1
1 2
2 3
3 NaN
4 a
dtype: object
[<class 'float'>, <class 'float'>, <class 'float'>, <class 'float'>, <class 'str'>]
以及:
输出:
0 1
1 2
2 3
3 NaN
4 a
dtype: object
[<class 'float'>, <class 'float'>, <class 'float'>, <class 'float'>, <class 'str'>]
[,]
我认为这是因为有三种类型:int、float和str。我甚至可以处理float的int,但不是所有str。谢谢您的回答!但是如果我在系列中有不同的字符串,比如“a”、“b”等,那就没用了@Pruntoff-你为什么这么认为?