假设我有一个列表
mix = numpy.array(['1.', '2.', 'a'])
如何在可能的情况下将字符串转换为float,以便我可以得到:
array([1., 2., 'a'])
我尝试将try / exception
与astype()
一起使用,但它不会转换单个元素。
更新:
在csv
包中,有csv.QUOTE_NONNUMERIC
,我想知道numpy
是否支持类似的内容。
答案 0 :(得分:4)
没有找到能让它发挥作用的功能,所以我写了一些适合你的东西。
def myArrayConverter(arr):
convertArr = []
for s in arr.ravel():
try:
value = float32(s)
except ValueError:
value = s
convertArr.append(value)
return array(convertArr,dtype=object).reshape(arr.shape)
干杯
答案 1 :(得分:2)
对于混合数据类型的数组,设置dtype=object
:
>>> mix = numpy.array(['1.', '2.', 'a'])
>>> mixed=[]
>>> for a in list(mix):
try:
mixed.append(float(a))
except:
mixed.append(a)
>>> mixed=numpy.array(mixed, dtype=object)
>>> mixed
array([1.0, 2.0, 'a'], dtype=object)
>>> type(mixed[0]),type(mixed[1]),type(mixed[2])
(<type 'float'>, <type 'float'>, <type 'numpy.string_'>)
希望它有所帮助。
答案 2 :(得分:0)
可行的一种方法是检查字符串是否与正则表达式匹配,如果是,则转换为float:
[float(x) if re.search('[0-9]*\.?[0-9]', x) else x for x in mix]