You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Python DataFrame数值列转为float类型且保留非数值列

修复DataFrame数值列转换函数:保留非数值列

原函数的问题在于,通过df.applymap(is_it_a_number)生成布尔矩阵后筛选,会把非数值列的所有元素置为NaN,随后dropna(how='all', axis=1)直接删除了这些包含重要信息的非数值列。

下面提供两种修复方案,按需选择:

方案1:仅转换完全可转为数值的列

适合需求:仅将所有元素都能转成数值的列转为数值类型,其余列完全保留原始状态(包括其中的非数值元素)

import pandas as pd

def convert_dataframe_to_numeric_type(df):
    converted_df = df.copy()
    
    for col in converted_df.columns:
        try:
            # 尝试转换整列,若有任何元素无法转换则抛出异常,跳过该列
            converted_df[col] = pd.to_numeric(converted_df[col], errors='raise')
        except ValueError:
            continue
    
    return converted_df

方案2:转换含有效数值的列(非数值元素转为NaN)

适合需求:只要列中存在可转换的数值元素,就将列转为数值类型,无法转换的元素设为NaN,完全无有效数值的列保留原始状态

import pandas as pd

def convert_dataframe_to_numeric_type(df):
    converted_df = df.copy()
    
    for col in converted_df.columns:
        temp_col = pd.to_numeric(converted_df[col], errors='coerce')
        # 若转换后不全是NaN,则替换原列
        if not temp_col.isna().all():
            converted_df[col] = temp_col
    
    return converted_df

这两种方案都不会删除任何列,既完成了数值列的类型转换,又完整保留了非数值列的原始数据。

内容的提问来源于stack exchange,提问作者Mainland

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 14:32:47