从大型数组中删除值组

时间:2016-12-08 10:44:09

标签: python arrays python-3.x

我有一个4列数组,在一列中,它们由大约6或7个不同的重复值组成。我想要做的是通过删除一种类型的数字和每个值的相关行来创建一组较小的数组。

例如:

1 2 3 4
3 6 5 4
3 2 9 8
5 3 0 8
4 6 9 5
7 3 4 7

在第二列中,重复2,3和6,如何提取第二列中包含3的所有行,然后将此结果放入新数组?

编辑:我忘了提到数据位于.dat文件中作为2D数组

2 个答案:

答案 0 :(得分:0)

使用Python列表

# construct a list contain all rows with column 'colm' value  'value' for a matrix 
# matrix is a list contain rows from file.dat eg formated [[],[],[]...]
def construct(colm, value, matrix):
    result = [] 
    for row in matrix:
        if row[colm-1] == value:
            result.append(row)
    return result

# Read file.dat and return list matrix
def read():
    var = []
    try:
        file = open("file.dat", 'r')
        for line in file:
            # append a list with a file.dat row, and convert each item to integer
            var.append([int(y) for y in line.strip().split(' ')])
    finally:
        file.close()
    return var

所以你可以用它作为

constuct(2, 3, read()) # all rows with second column with value 3

注意:我还没有对NumPy进行过多探索,但如果你的.dat文件包含大量数据,那么use NumPy instead of lists就可以了解有效的操作。

答案 1 :(得分:0)

您可以使用numpy的布尔索引功能

>>> import numpy as np
>>> data = np.array([[1, 2, 3, 4], 
                     [3, 6, 5, 4], 
                     [3, 2, 9, 8], 
                     [5, 3, 0, 8], 
                     [4, 6, 9, 5], 
                     [7, 3, 4, 7]])

>>> print(data[data[:,1] == 3, :])
[[5 3 0 8]
 [7 3 4 7]]