Skip to main content
 首页 » 编程设计

python之Pandas :仅将数据框中的数字转换为数字,保留其他所有内容

2025年05月04日21jyk

源数据框

df1 = pd.DataFrame({'x': ['a', '2.0', '3.0'], 'y': ['4.0', 'b', '6.0']}) 
 
    x   y 
0   a   4.0 
1   2.0 b 
2   3.0 6.0 

第一次尝试(使用'强制')

如果我使用 'coerce' 来处理字符串,它们将被 NaN 取代

df2 = df1.apply(lambda x: pd.to_numeric(x.astype(str).str.replace(',',''), errors='coerce')) 
 
    x   y 
0   NaN 4.0 
1   2.0 NaN 
2   3.0 6.0 

第二次尝试(使用'忽略')

如果我使用“忽略”来处理字符串,则不会转换整列(数字仍保留为文本字符串)

df2 = df1.apply(lambda x: pd.to_numeric(x.astype(str).str.replace(',',''), errors='ignore')) 
 
    x   y 
0   a   4.0 
1   2.0 b 
2   3.0 6.0 

请您参考如下方法:

这是预期的输出,因为如果检查 to_numeric你可以看到:

errors : {'ignore', 'raise', 'coerce'}, default 'raise'

If 'raise', then invalid parsing will raise an exception
If 'coerce', then invalid parsing will be set as NaN
If 'ignore', then invalid parsing will return the input

可能的解决方案是用原始值替换缺失值 - 但得到混合数字和字符串值,如评论中指出的@anky_91:

df2 = df1.apply(lambda x: pd.to_numeric(x.astype(str).str.replace(',',''), errors='coerce')) 

df3 = df2.fillna(df1) 

或者:

df3 = df2.combine_first(df1) 

检查类型:

print (df3.applymap(type)) 
                 x                y 
0    <class 'str'>  <class 'float'> 
1  <class 'float'>    <class 'str'> 
2  <class 'float'>  <class 'float'>