Skip to main content
 首页 » 编程设计

python之如何找到哪些单元格无法转换为 float

2024年10月24日8lidabo

pandas.DataFrame.astype(float) 引发 ValueError: could not convert string to float 错误。

找到导致这种情况发生的细胞的最佳方法是什么?

请您参考如下方法:

我觉得你可以先fillna有一些数字,例如1,apply函数 to_numeric带有参数 errors='coerce',如果无法转换值,则由 NaN 填充。然后你检查isnull与 any .最后使用boolean indexing用于查找具有 NaN 值的列和索引 - 这意味着显然存在 string 值或其他无法转换为数字的值。

import pandas as pd 
import numpy as np 
 
df = pd.DataFrame({'A':['a','b','',5], 
                   'B':[4,5,6,5], 
                   'C':[np.nan,8,9,7]}) 
 
print (df) 
   A  B    C 
0  a  4  NaN 
1  b  5  8.0 
2     6  9.0 
3  5  5  7.0 
a = (df.fillna(1).apply(lambda x: pd.to_numeric(x, errors='coerce'))) 
print (a) 
     A  B    C 
0  NaN  4  1.0 
1  NaN  5  8.0 
2  NaN  6  9.0 
3  5.0  5  7.0 
 
b = (pd.isnull(a)) 
print (b) 
       A      B      C 
0   True  False  False 
1   True  False  False 
2   True  False  False 
3  False  False  False 
print (b.any()) 
A     True 
B    False 
C    False 
dtype: bool 
 
print (b.any()[b.any()].index) 
Index(['A'], dtype='object') 
 
print (b.any(axis=1)) 
0     True 
1     True 
2     True 
3    False 
dtype: bool 
 
print (b.any(axis=1)[b.any(axis=1)].index) 
Int64Index([0, 1, 2], dtype='int64') 
 
#df is not modified 
print (df) 
   A  B    C 
0  a  4  NaN 
1  b  5  8.0 
2     6  9.0 
3  5  5  7.0