使用numpy根据状态删除列

问题描述 投票:0回答:2

我进行了一系列实验,完成后我意识到它们中有一定数量不可靠,所以我想删除它们。我决定为此目的添加另一个数组status,其中我想要保留的列被定义为True,而我想要删除的列被表示为False

import numpy as np

data_a = np.arange(1,14)
status = np.array([False, True, False, True, True, True, True, True, True, False, True, True, True])

test = []
for stats, da in zip(status, data_a):
    if stats == True:
        data_a = da
        test.append(data_a)
    elif stats == False:
        pass
    else:
        print('Impossible -- in the case of status, there exist only two conditionals (True or False).')

在最简单的情况下,没有问题,它似乎通过提供以下输出按预期工作:

[2, 4, 5, 6, 7, 8, 9, 11, 12, 13]

但是,我正在处理几个数据集(不仅仅是一个,在这种情况下,data_a)。因此,我决定通过添加两个新数组使其变得更加困难:

data_b = np.arange(101,114)
data_c = np.arange(1001,1014)

test = []
for datasets in (data_a, data_b, data_c):
    for stats, sets in zip(status, datasets):
        if stats == True:
            datasets = sets
            test.append(datasets)
        elif stats == False:
            pass
        else:
            print('Impossible -- in the case of status, there exist only two conditionals (True or False).')

这个稍微复杂的案例提供了:

[2, 4, 5, 6, 7, 8, 9, 11, 12, 13, 102, 104, 105, 106, 107, 108, 109, 111, 112, 113, 1002, 1004, 1005, 1006, 1007, 1008, 1009, 1011, 1012, 1013]

它完成了我的要求,但是我需要做些什么才能将data_adata_bdata_c独立存储为数组?

在最复杂的情​​况下(对于我实际上做的事情也是如此),我的数据集实际上是形状为(11,13)的数组:

data_a = []
data_b = []
data_c = []

for dtlsts in (data_a, data_b, data_c):
    for _ in range(11):
        dtlsts.append(np.random.randint(0, 10, 13))

data_a = np.array(data_a)
data_b = np.array(data_b)
data_c = np.array(data_c)

因此,我想:

  • 根据状态数组删除列,所以我最终得到形状为(11,10)的数组。
  • 独立存储这些数组(即data_adata_bdata_c都存储在独立的(11,10)数组中)。

我在深水中,真的很感激一些帮助。谢谢。

python numpy
2个回答
1
投票

如果我理解了这个问题,你可以这样做:

test = [ [] for _ in range(3) ]
for i, state in enumerate(status):
  if state:
    test[0].append(data_a[i])
    test[1].append(data_b[i])
    test[2].append(data_c[i])

print(test)
#=> [[2, 4, 5, 6, 7, 8, 9, 11, 12, 13], [102, 104, 105, 106, 107, 108, 109, 111, 112, 113], [1002, 1004, 1005, 1006, 1007, 1008, 1009, 1011, 1012, 1013]]

1
投票

要扩展@Andrew的注释,您可以使用像这样的布尔掩码对整列进行索引。

In [120]: data_a = np.arange(1,14)
     ...: status = np.array([False, True, False, True, True, True, True, True, True, False, True, True, True])
     ...: 
     ...: 
In [121]: data_a
Out[121]: array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13])
In [122]: data_a[status]
Out[122]: array([ 2,  4,  5,  6,  7,  8,  9, 11, 12, 13])

对于2d数组,请调整索引:

In [123]: data_b = np.vstack([data_a,data_a,data_a])
In [124]: data_b[:,status]
Out[124]: 
array([[ 2,  4,  5,  6,  7,  8,  9, 11, 12, 13],
       [ 2,  4,  5,  6,  7,  8,  9, 11, 12, 13],
       [ 2,  4,  5,  6,  7,  8,  9, 11, 12, 13]])
© www.soinside.com 2019 - 2024. All rights reserved.