我从一个实验中选择了一些值,我想删除一些相对于其他行的行。意义:我测量一个场,一个极化和一个偏振的误差。现在,进行这种测量的机器有时不会在其中的一些行中写入值。所以我可能得到: field = data
field = [1,2,3,3,2,1,nan,4,1,2]
polarization = [nan, 10,230,13,123,50,102,90,45]
error = [0.1, 0.1, 0.2, 0.1, 0.1, 0.3, 0.1, 0.1, 0.4, 0.2]
现在,我想删除字段、极化和误差的第一个元素,因为极化值= nan。以及所有数组的6个值,因为field6 = nan。
我就是这样得到数据的:
class DataFile(object):
def __init__(self, filename):
self._filename = filename
def read_dat_file(self):
data = np.genfromtxt(self._filename, delimiter=',', \
usecols=(3,4,5,), skip_header=23, skip_footer=3, unpack=True, converters={\
3: lambda x: self._conv(x), \
4: lambda x: self._conv(x), \
5: lambda x: self._2_conv(x)})
return data
a = DataFile("DATFILE.DAT")
print a
如果值为“”,_conv函数只执行一些单元转换或编写'nan‘。我试着做这样的事情:
data = data[~np.isnan(data).any(axis=1)]
但后来我又回到了一个数组,事情变得很混乱。我的下一个方法是计数元素,从所有数组中删除相同的元素.诸若此类。很管用,但很丑。那么这里最好的解决方案是什么呢?
发布于 2015-03-03 09:33:21
您可以遍历行并为行创建掩码,然后使用布尔索引获取传递的行的视图:
import numpy as np
field = [1,2,3,3,2,1,-1,4,1,2]
polarization = [-1, 10,230,13,123,50,102,90,45,1337]
error = [0.1, 0.1, 0.2, 0.1, 0.1, 0.3, 0.1, 0.1, 0.4, 0.2]
#transposition is needed to get expected row-col format
array = np.array([field, polarization, error]).T
print(array)
#create your filter function
filter = lambda row : row[0] > 0 and row[1] > 0 and row[2] > 0
#create boolean mask by applying filter
mask = np.apply_along_axis(filter, 1, array)
print(mask)
new_array = array[mask]
print(new_array)
发布于 2015-03-03 08:49:42
尝试使用mask_where
命令。
一个(非常基本的)例子:
y = np.array([2,1,5,2]) # y axis
x = np.array([1,2,3,4]) # x axis
m = np.ma.masked_where(y>5, y) # filter out values larger than 5
new_x = np.ma.masked_where(np.ma.getmask(m), x) # applies the mask of m on x
更好的是,您现在可以将此掩码应用于更多的数组,而无需对每个数组进行掩蔽处理。而且它也不会像计算元素那样丑陋。
在您的示例中,您可能需要遍历每个数组,检查是否为nan
,然后将该掩码应用于所有其他数组。希望这能有所帮助。
发布于 2015-03-03 13:16:58
我组合了另一个线程和red_tigers答案,并希望与您共享它:只需在数组上运行这个函数,其中包含数据:
data = np.array([field, polarization, error]).T
def delete_NaN_rows(self, data):
filter = lambda row: ~np.isnan(row[0]) and ~np.isnan(row[1]) and ~np.isnan(row[2])
mask = np.apply_along_axis(filter, 1, data)
clean_data = data[mask]
return clean_data.T
我使用了np.isnan(#element)的逆(~),用一个NaN条目标识我的行并删除它们。
https://stackoverflow.com/questions/28827282
复制相似问题