Python中处理混合类型NumPy数组并提取数值型数据的方法
本文探讨在Python中处理包含字符与数值的混合类型NumPy数组(dtype为字符串)时,如何有效提取纯数值数据。由于math.isnan和np.isnan均无法直接处理此类数组,文章提供了两种解决方案:一是转换为列表后过滤但丢失索引;二是利用map生成布尔数组,结合pandas DataFrame保留原始索引信息,从而实现数据与索引的同步过滤。
当NumPy数组同时包含数值与字符时,无法直接识别其中的数值型数据。这是因为混合类型会导致数组的dtype变为字符串类型(如'<U11'),从而不再被视为数值型数组,使得常规的数值判断方法失效。
首先,使用math.isnan函数无法解决问题,因为它仅能判断float("nan")类型的值。
>>> import math
>>> math.isnan(1)
False
>>> math.isnan('a')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: a float is required
>>> math.isnan(float("nan"))
True
>>>
其次,np.isnan函数也不适用,因为它要求输入必须是数值型数组且包含np.nan,否则无法执行。
>>> import numpy as np >>> test1=np.array([1,2,'aa',3]) >>> np.isnan(test1) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''sa fe'' >>> test2=np.array([1,2,np.nan,3]) >>> np.isnan(test2) array([False, False, True, False], dtype=bool) >>>
针对上述限制,可以采取以下解决策略:
方法1:将NumPy数组转换为Python列表,利用filter函数筛选出数值型元素,再转换回NumPy数组。然而,这种方法存在一个显著缺陷:无法保证保留原始数据的索引位置。
>>> import numpy as np >>> test1=np.array([1,2,'aa',3]) >>> list1=list(test1) >>> def filter_fun(x): ... try: ... return isinstance(float(x),(float)) ... except: ... return False ... >>> list(filter(filter_fun,list1)) ['1', '2', '3'] >>> np.array(filter(filter_fun,list1)) array(<filter object at 0x0339CA30>, dtype=object) >>> np.array(list(filter(filter_fun,list1))) array(['1', '2', '3'], dtype='<U1') >>> np.array([float(x) for x in filter(filter_fun,list1)]) array([ 1., 2., 3.]) >>>
方法2:利用map函数构建布尔数组,进而对数据和索引进行同步过滤。
>>> import numpy as np >>> test1=np.array([1,2,'aa',3]) >>> list1=list(test1) >>> def filter_fun(x): ... try: ... return isinstance(float(x),(float)) ... except: ... return False ... >>> import pandas as pd >>> test=pd.DataFrame(test1,index=[1,2,3,4]) >>> test 0 1 1 2 2 3 aa 4 3 >>> index=test.index >>> index Int64Index([1, 2, 3, 4], dtype='int64') >>> bool_index=map(filter_fun,list1) >>> bool_index=list(bool_index) #bool_index这样的迭代结果只能list一次,一次再list时会是空,所以保存一下list的结果 >>> bool_index [True, True, False, True] >>> new_data=test1[np.array(bool_index)] >>> new_data array(['1', '2', '3'], dtype='<U11') >>> new_index=index[np.array(bool_index)] >>> new_index Int64Index([1, 2, 4], dtype='int64') >>> test2=pd.DataFrame(new_data,index=new_index) >>> test2 0 1 1 2 2 4 3 >>>
以上即为处理NumPy混合类型数组并提取数值型数据的相关方法,希望能为读者提供有效参考。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













