使用Numpy将空字符串转换为0 [英] Converting empty strings to 0 using Numpy

查看:392
本文介绍了使用Numpy将空字符串转换为0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个numpy数组,其中每个元素看起来都像这样:

I have a numpy array where each element looks something like this:

['3' '1' '35' '0' '0' '8.05' '2']
['3' '1' '' '0' '0' '8.4583' '0']
['1' '1' '54' '0' '0' '51.8625' '2']

我想用上面的默认值(如0)替换上面第二行中的所有空字符串.如何用numpy做到这一点?

I would like to replace all empty strings like the ones in the second row above, with some default value like 0. How can I do this with numpy?

最终目标是能够运行以下命令:S.astype(np.float),但是我怀疑空字符串会导致转换问题.

The ultimate goal is to be able to run this: S.astype(np.float), but I suspect the empty strings are causing problems in the conversion.

推荐答案

如果您的数组是t:

t[t=='']='0'

然后将其转换.

说明:

t==''创建一个具有与t相同形状的布尔数组,该数组具有True值,其中对应的t值为空白.然后,此布尔数组用于将'0'仅分配给原始t中的适当索引.

t=='' creates a boolean array with the same shape as t that has a True value where the corresponding t value is an empty space. This boolean array is then used to assign '0' only to the appropriate indices in the original t.

这篇关于使用Numpy将空字符串转换为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆