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

如何将混合字符串和数字的二维numpy数组转float数组且字符串转nan(不使用Pandas)

Numpy 混合元素字符串数组转Float数组方案

需求说明

  • 输入为混合数字、字符串元素的numpy str类型二维数组
  • 输出为float类型numpy数组,所有无法转为数字的元素统一替换为nan
  • 不得引入Pandas库

示例输入

import numpy as np
x = np.array([[1, 2, 'tom'], [4, 'Manu', 6]])

实现方法

方法1:通用兼容写法(适配所有数字格式)

通过自定义转换函数处理每个元素,转换失败则返回nan,使用np.vectorize实现批量处理:

def str_to_float(element):
    try:
        return float(element)
    except ValueError:
        return np.nan

vec_convert = np.vectorize(str_to_float)
x = vec_convert(x).astype(float)

方法2:简洁高效写法

借助np.genfromtxt原生的无效值处理逻辑,一行完成转换,性能更优:

x = np.genfromtxt(x.astype(str).flatten(), dtype=float).reshape(x.shape)

最终输出

两种方法运行后均会得到预期结果:
x = np.array([[ 1., 2., nan], [ 4., nan, 6.]])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 02:09:03