蟒蛇。按条件从数组(显示为列表列表)中删除行和列

时间:2015-01-25 15:33:03

标签: python numpy

我有一个列表列表,我需要删除所有行,然后删除值大于某个变量的列。 我无法找到自己如何做到这一点。 我所能做的就是:

rowNum =0
for row in self.Table:
    rowIsValid = False
    for value in row:
        if not value is None and (value > 0.35 and not value == 1):
            rowIsValid = True
    if not rowIsValid:
        self.Table =  numpy.delete(self.Table, (rowNum), axis=0)
        #self.Table.pop(row)
    rowNum+=1

我只是为了行。它不起作用( 如何删除列 - 我甚至无法想象。

数据示例 输入:

 1.0 None 0.333 0.166 None
 0.4 1.0  0.541 0.4   0.3
 0.1 0.41 1.0   0.23  0.11

输出(例如我需要删除所有值小于0.3而不是(1不包含在计算中)的行和列)

0.4 1.0  0.541 0.4  
0.1 0.41 1.0   0.23 

1 个答案:

答案 0 :(得分:0)

如果您的数组看起来像这样:

>>> arr = array([[ 1.   ,    nan,  0.333,  0.166,    nan],
       [ 0.4  ,  1.   ,  0.541,  0.4  ,  0.3  ],
       [ 0.1  ,  0.41 ,  1.   ,  0.23 ,  0.11 ]])

然后首先将所有nan值设置为True,因为它们不符合标准。

>>> arr[np.isnan(arr)] = True

现在获取一组布尔值,其中True表示符合我们条件的项目,现在如果行或列中的所有项目都是True,那么我们应该忽略该行或列:

>>> temp = (arr == 1.0) | (arr < 0.35)
>>> temp
array([[ True,  True,  True,  True,  True],
       [False,  True, False, False,  True],
       [ True, False,  True,  True,  True]], dtype=bool)

仅获取包含至少一个False的行:

>>> rows = ~np.all(temp, axis=1)
>>> rows
array([False,  True,  True], dtype=bool)

与行相同,但在不同的轴上:

>>> cols = ~np.all(temp, axis=0)
>>> cols
array([ True,  True,  True,  True, False], dtype=bool)

现在使用简单的索引和切片来获取所需的项目:

>>> arr[rows][:, cols]
array([[ 0.4  ,  1.   ,  0.541,  0.4  ],
       [ 0.1  ,  0.41 ,  1.   ,  0.23 ]])
相关问题